|
| 1 | +package electrum |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/hex" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/btcsuite/btcd/wire" |
| 9 | + |
| 10 | + "github.com/keep-network/keep-core/pkg/bitcoin" |
| 11 | +) |
| 12 | + |
| 13 | +// decodeTransaction deserializes a transaction from the hexadecimal serialized |
| 14 | +// string to a btcd message format. |
| 15 | +func decodeTransaction(rawTx string) (*wire.MsgTx, error) { |
| 16 | + headerBytes, err := hex.DecodeString(rawTx) |
| 17 | + if err != nil { |
| 18 | + return nil, fmt.Errorf("failed to decode a hex string: [%w]", err) |
| 19 | + } |
| 20 | + |
| 21 | + buf := bytes.NewBuffer(headerBytes) |
| 22 | + |
| 23 | + var t wire.MsgTx |
| 24 | + if err := t.Deserialize(buf); err != nil { |
| 25 | + return nil, fmt.Errorf("failed to deserialize a transaction: [%w]", err) |
| 26 | + } |
| 27 | + |
| 28 | + return &t, nil |
| 29 | +} |
| 30 | + |
| 31 | +// convertRawTransaction transforms a transaction provided in the hexadecimal serialized |
| 32 | +// string to the format expected by the bitcoin.Chain interface. |
| 33 | +func convertRawTransaction(rawTx string) (*bitcoin.Transaction, error) { |
| 34 | + t, err := decodeTransaction(rawTx) |
| 35 | + if err != nil { |
| 36 | + return nil, fmt.Errorf("failed to decode a transaction: [%w]", err) |
| 37 | + } |
| 38 | + |
| 39 | + result := &bitcoin.Transaction{ |
| 40 | + Version: int32(t.Version), |
| 41 | + Locktime: t.LockTime, |
| 42 | + } |
| 43 | + |
| 44 | + for _, vin := range t.TxIn { |
| 45 | + input := &bitcoin.TransactionInput{ |
| 46 | + Outpoint: &bitcoin.TransactionOutpoint{ |
| 47 | + TransactionHash: bitcoin.Hash(vin.PreviousOutPoint.Hash), |
| 48 | + OutputIndex: vin.PreviousOutPoint.Index, |
| 49 | + }, |
| 50 | + SignatureScript: vin.SignatureScript, |
| 51 | + Sequence: vin.Sequence, |
| 52 | + } |
| 53 | + |
| 54 | + result.Inputs = append(result.Inputs, input) |
| 55 | + } |
| 56 | + |
| 57 | + for _, vout := range t.TxOut { |
| 58 | + output := &bitcoin.TransactionOutput{ |
| 59 | + Value: vout.Value, |
| 60 | + PublicKeyScript: vout.PkScript, |
| 61 | + } |
| 62 | + |
| 63 | + result.Outputs = append(result.Outputs, output) |
| 64 | + } |
| 65 | + |
| 66 | + return result, nil |
| 67 | +} |
0 commit comments