|
| 1 | +package vaultpoly |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/hex" |
| 7 | + "encoding/json" |
| 8 | + "math/big" |
| 9 | + "strings" |
| 10 | + "testing" |
| 11 | + |
| 12 | + btcec "github.com/btcsuite/btcd/btcec/v2" |
| 13 | + "github.com/btcsuite/btcd/btcec/v2/ecdsa" |
| 14 | + "github.com/btcsuite/btcd/btcutil" |
| 15 | + "github.com/btcsuite/btcd/chaincfg" |
| 16 | + "github.com/btcsuite/btcd/txscript" |
| 17 | + "github.com/btcsuite/btcd/wire" |
| 18 | + "github.com/ethereum/go-ethereum/core/types" |
| 19 | + "github.com/ethereum/go-ethereum/rlp" |
| 20 | + "github.com/hashicorp/vault/sdk/logical" |
| 21 | + "github.com/igwedaniel/vaultpoly/internal/adapters" |
| 22 | + "github.com/stretchr/testify/require" |
| 23 | +) |
| 24 | + |
| 25 | +func TestImportAndSign(t *testing.T) { |
| 26 | + b, s := getTestBackend(t) |
| 27 | + |
| 28 | + t.Run("Import and sign ETH", func(t *testing.T) { |
| 29 | + testImportAndSignETH(t, b, s) |
| 30 | + }) |
| 31 | + |
| 32 | + t.Run("Import and sign BTC", func(t *testing.T) { |
| 33 | + testImportAndSignBTC(t, b, s) |
| 34 | + }) |
| 35 | +} |
| 36 | + |
| 37 | +func testImportAndSignETH(t *testing.T, b *pluginBackend, s logical.Storage) { |
| 38 | + importResp, err := testWalletImport(t, b, s, adapters.BlockchainETH.String(), |
| 39 | + "aa18efe8e8b1da4488e9f1350ad1f25ad387229177907ddb5c57e9cc22a74592") |
| 40 | + require.NoError(t, err) |
| 41 | + require.NotNil(t, importResp) |
| 42 | + require.Nil(t, importResp.Error()) |
| 43 | + |
| 44 | + address := importResp.Data["address"].(string) |
| 45 | + require.NotEmpty(t, address) |
| 46 | + |
| 47 | + payload := adapters.EthPayload{ |
| 48 | + ChainID: 97, |
| 49 | + To: "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", |
| 50 | + Value: 0, |
| 51 | + Data: "0xa9059cbb000000000000000000000000253f9dd15f4bd360595b0e83d51ef31d8e71d31b0000000000000000000000000000000000000000000000000de0b6b3a7640000", |
| 52 | + Nonce: 0, |
| 53 | + GasLimit: 60000, |
| 54 | + GasPrice: 1000000000, |
| 55 | + } |
| 56 | + jsonB, _ := json.Marshal(payload) |
| 57 | + |
| 58 | + signResp, err := testWalletSign(t, b, s, adapters.BlockchainETH.String(), address, map[string]interface{}{ |
| 59 | + "payload": string(jsonB), |
| 60 | + }) |
| 61 | + require.NoError(t, err) |
| 62 | + require.NotNil(t, signResp) |
| 63 | + require.Nil(t, signResp.Error()) |
| 64 | + |
| 65 | + signature := signResp.Data["signature"].(string) |
| 66 | + require.NotEmpty(t, signature) |
| 67 | + |
| 68 | + txBytes, err := hex.DecodeString(strings.TrimPrefix(signature, "0x")) |
| 69 | + require.NoError(t, err, "Failed to decode transaction hex") |
| 70 | + |
| 71 | + var tx types.Transaction |
| 72 | + err = rlp.DecodeBytes(txBytes, &tx) |
| 73 | + require.NoError(t, err, "Failed to decode RLP transaction") |
| 74 | + |
| 75 | + require.NotNil(t, tx.To(), "Transaction should have a recipient") |
| 76 | + require.Equal(t, uint64(payload.GasLimit), tx.Gas()) |
| 77 | + require.Equal(t, uint64(payload.Nonce), tx.Nonce()) |
| 78 | + require.Equal(t, strings.TrimPrefix(payload.Data, "0x"), hex.EncodeToString(tx.Data())) |
| 79 | + require.Equal(t, strings.ToLower(payload.To), strings.ToLower(tx.To().Hex())) |
| 80 | + |
| 81 | + expectedValue := big.NewInt(int64(payload.Value)) |
| 82 | + require.Equal(t, 0, expectedValue.Cmp(tx.Value())) |
| 83 | + |
| 84 | + expectedGasPrice := big.NewInt(int64(payload.GasPrice)) |
| 85 | + require.Equal(t, 0, expectedGasPrice.Cmp(tx.GasPrice())) |
| 86 | + |
| 87 | + chainID := big.NewInt(int64(payload.ChainID)) |
| 88 | + signer := types.NewEIP155Signer(chainID) |
| 89 | + recoveredAddress, err := types.Sender(signer, &tx) |
| 90 | + require.NoError(t, err, "Failed to recover signer address") |
| 91 | + require.Equal(t, strings.ToLower(address), strings.ToLower(recoveredAddress.Hex()), |
| 92 | + "Recovered signer address doesn't match imported wallet address") |
| 93 | +} |
| 94 | + |
| 95 | +func testImportAndSignBTC(t *testing.T, b *pluginBackend, s logical.Storage) { |
| 96 | + pk, err := btcec.NewPrivateKey() |
| 97 | + require.NoError(t, err) |
| 98 | + wif, err := btcutil.NewWIF(pk, &chaincfg.TestNet4Params, true) |
| 99 | + require.NoError(t, err) |
| 100 | + |
| 101 | + importResp, err := testWalletImport(t, b, s, adapters.BlockchainBTCTestnet.String(), wif.String()) |
| 102 | + require.NoError(t, err) |
| 103 | + require.NotNil(t, importResp) |
| 104 | + require.Nil(t, importResp.Error()) |
| 105 | + |
| 106 | + address := importResp.Data["address"].(string) |
| 107 | + require.NotEmpty(t, address) |
| 108 | + |
| 109 | + addr, err := btcutil.DecodeAddress(address, &chaincfg.TestNet4Params) |
| 110 | + require.NoError(t, err) |
| 111 | + script, err := txscript.PayToAddrScript(addr) |
| 112 | + require.NoError(t, err) |
| 113 | + |
| 114 | + addressPubScriptKey := hex.EncodeToString(script) |
| 115 | + utxos := []adapters.UTXO{ |
| 116 | + { |
| 117 | + Txid: "9404a6b8f40b9fd4b868b0305a16eddfd1bcd8477c2f71bbc1588ba8884208c3", |
| 118 | + Vout: 1, |
| 119 | + Value: 500000, |
| 120 | + ScriptPubKey: addressPubScriptKey, |
| 121 | + ScriptPubKeyType: "v0_p2wpkh", |
| 122 | + }, |
| 123 | + } |
| 124 | + |
| 125 | + amount := int64(200000) |
| 126 | + recipient := "tb1qpn5dddjnc2qwurpsm449l6uvggnjxwsetrnksx" |
| 127 | + payload := testBtcPayload(amount, recipient, utxos) |
| 128 | + |
| 129 | + signResp, err := testWalletSign(t, b, s, adapters.BlockchainBTCTestnet.String(), address, map[string]interface{}{ |
| 130 | + "payload": payload, |
| 131 | + }) |
| 132 | + require.NoError(t, err) |
| 133 | + require.NotNil(t, signResp) |
| 134 | + require.Nil(t, signResp.Error()) |
| 135 | + |
| 136 | + signature := signResp.Data["signature"].(string) |
| 137 | + require.NotEmpty(t, signature) |
| 138 | + |
| 139 | + txBytes, err := hex.DecodeString(signature) |
| 140 | + require.NoError(t, err) |
| 141 | + |
| 142 | + var tx wire.MsgTx |
| 143 | + err = tx.Deserialize(bytes.NewReader(txBytes)) |
| 144 | + require.NoError(t, err, "Transaction should deserialize") |
| 145 | + require.Equal(t, 2, len(tx.TxOut), "Expected 2 outputs (recipient + change)") |
| 146 | + |
| 147 | + recipientAddr, err := btcutil.DecodeAddress(recipient, &chaincfg.TestNet4Params) |
| 148 | + require.NoError(t, err) |
| 149 | + recipientScript, err := txscript.PayToAddrScript(recipientAddr) |
| 150 | + require.NoError(t, err) |
| 151 | + require.True(t, bytes.Equal(tx.TxOut[0].PkScript, recipientScript), "Recipient script mismatch") |
| 152 | + require.Equal(t, amount, tx.TxOut[0].Value, "Recipient amount mismatch") |
| 153 | + |
| 154 | + utxo := utxos[0] |
| 155 | + prevScript, err := hex.DecodeString(utxo.ScriptPubKey) |
| 156 | + require.NoError(t, err) |
| 157 | + |
| 158 | + txIn := tx.TxIn[0] |
| 159 | + require.NotEmpty(t, txIn.Witness, "P2WPKH transaction should have witness data") |
| 160 | + require.Equal(t, 2, len(txIn.Witness), "P2WPKH witness should have 2 elements (signature + pubkey)") |
| 161 | + |
| 162 | + sigBytes := txIn.Witness[0] |
| 163 | + pubKeyBytes := txIn.Witness[1] |
| 164 | + |
| 165 | + sigBytesNoHashType := sigBytes[:len(sigBytes)-1] |
| 166 | + parsedSig, err := ecdsa.ParseDERSignature(sigBytesNoHashType) |
| 167 | + require.NoError(t, err, "Failed to parse signature") |
| 168 | + |
| 169 | + pubKey, err := btcec.ParsePubKey(pubKeyBytes) |
| 170 | + require.NoError(t, err, "Failed to parse public key") |
| 171 | + |
| 172 | + hash := btcutil.Hash160(pubKey.SerializeCompressed()) |
| 173 | + derivedAddr, err := btcutil.NewAddressWitnessPubKeyHash(hash, &chaincfg.TestNet4Params) |
| 174 | + require.NoError(t, err) |
| 175 | + require.Equal(t, address, derivedAddr.EncodeAddress(), |
| 176 | + "Signing public key doesn't match imported wallet address") |
| 177 | + |
| 178 | + sigHashes := txscript.NewTxSigHashes(&tx, txscript.NewCannedPrevOutputFetcher(prevScript, utxo.Value)) |
| 179 | + sigHash, err := txscript.CalcWitnessSigHash(prevScript, sigHashes, txscript.SigHashAll, &tx, 0, utxo.Value) |
| 180 | + require.NoError(t, err) |
| 181 | + require.True(t, parsedSig.Verify(sigHash, pubKey), "Signature verification failed") |
| 182 | + |
| 183 | + prevOutputFetcher := txscript.NewCannedPrevOutputFetcher(prevScript, utxo.Value) |
| 184 | + engine, err := txscript.NewEngine(prevScript, &tx, 0, txscript.StandardVerifyFlags, nil, nil, utxo.Value, prevOutputFetcher) |
| 185 | + require.NoError(t, err) |
| 186 | + err = engine.Execute() |
| 187 | + require.NoError(t, err, "Script execution failed - transaction signature is invalid") |
| 188 | + |
| 189 | + totalOutput := int64(0) |
| 190 | + for _, out := range tx.TxOut { |
| 191 | + totalOutput += out.Value |
| 192 | + } |
| 193 | + actualFee := utxo.Value - totalOutput |
| 194 | + require.True(t, actualFee > 0, "Transaction fee should be positive") |
| 195 | +} |
| 196 | + |
| 197 | +func testWalletImport(t *testing.T, b *pluginBackend, s logical.Storage, blockchainType string, privateKey string) (*logical.Response, error) { |
| 198 | + t.Helper() |
| 199 | + return b.HandleRequest(context.Background(), &logical.Request{ |
| 200 | + Operation: logical.UpdateOperation, |
| 201 | + Path: "wallets/" + blockchainType + "/import", |
| 202 | + Data: map[string]interface{}{ |
| 203 | + "private_key": privateKey, |
| 204 | + }, |
| 205 | + Storage: s, |
| 206 | + }) |
| 207 | +} |
0 commit comments