Skip to content

Transaction

shigeyuki azuchi edited this page Aug 22, 2023 · 3 revisions

Transaction can be processed with Tapyrus::Tx class.

Parsing transaction payload

Tapyrus::Tx#parse_from_payload method parses the transaction payload (binary) and creates a Transaction object.

tx = Tapyrus::Tx.parse_from_payload('010000000201e4a0f1fa83c642b91feafae36a0f8fded4158dfa6fd650e046b4364b805684000000006b483045022045c65646abc12c71352335dbec2824b2dbdef9253366b4b83439b2190ce098d2022100eed0b70371d3892f865b43e2bb713ec9e887a50d38f47e8416220daf826d0ab201210259f6658325c4e3ca6fb38f657ffcbf4b1c45ef4f0c1dd86d5f6c0cebb0e09520ffffffff31137db564a7fad07c9db5b6b862786589977c68d1270819030a9079941ca6c9010000006b48304502204354565632eedd30fb9ca5c22bb70ef848afd74f7bed354d267705a6e71ea885022100e6ea6250d29dc109cb59ac66318f1cb2768c13fb0daca7c3d91a3b8d0991e0cb01210259f6658325c4e3ca6fb38f657ffcbf4b1c45ef4f0c1dd86d5f6c0cebb0e09520ffffffff02801d2c04000000001976a914322653c91d6038e08b6d971e4560842c155c8a8888ac80248706000000001976a9143b9722f91a2e50d913dadc3a6a8a88a58a7b859788ac00000000'.htb)

On the other hand, you can generate a transaction payload (binary) from a transaction object with the Tapyrus::Tx#to_payload method.

payload = tx.to_payload

Create transaction

You can also create transactions from scratch with Tapyrus::Tx.

tx = Tapyus::Tx.new

# add input
tx.in << Tapyrus::TxIn.new(out_point: Tapyrus::OutPoint.from_txid('75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858', 0))

# add output
tx.out << Tapyrus::TxOut.new(value: 15000, script_pubkey: Tapyrus::Script.parse_from_addr('191arn68nSLRiNJXD8srnmw4bRykBkVv6o'))

# sign transaction
input_index = 0
script_pubkey = Tapyrus::Script.parse_from_payload('00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1'.htb) # script pubkey of input 0

## generate sighash with SIGHASH_ALL
sig_hash = tx.sighash_for_input(input_index, script_pubkey)

## if use other sighash, you can specify hash_type option
sig_hash = tx.sighash_for_input(input_index, script_pubkey, hash_type: Tapyrus::SIGHASH_TYPE[:single])

## generate signature
key = Tapyrus::Key.from_base58('xxxxxx')
signature = key.sign(sig_hash) + [Tapyrus::SIGHASH_TYPE[:all]].pack('C')

## set signature to input
tx.in[0].script_sig << signature
tx.in[0].script_sig << key.pubkey.htb

## verify signature and script
tx.verify_input_sig(0, script_pubkey)
=> true/false

# show txid
tx.txid

# show hash(txid and tx_hash differ only in endianness)
tx.tx_hash
Clone this wiki locally