MCPcopy Create free account
hub / github.com/jimmysong/programmingbitcoin / TxIn

Class TxIn

code-ch08/tx.py:250–316  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

248
249
250class TxIn:
251
252 def __init__(self, prev_tx, prev_index, script_sig=None, sequence=0xffffffff):
253 self.prev_tx = prev_tx
254 self.prev_index = prev_index
255 if script_sig is None:
256 self.script_sig = Script()
257 else:
258 self.script_sig = script_sig
259 self.sequence = sequence
260
261 def __repr__(self):
262 return '{}:{}'.format(
263 self.prev_tx.hex(),
264 self.prev_index,
265 )
266
267 @classmethod
268 def parse(cls, s):
269 '''Takes a byte stream and parses the tx_input at the start
270 return a TxIn object
271 '''
272 # prev_tx is 32 bytes, little endian
273 prev_tx = s.read(32)[::-1]
274 # prev_index is an integer in 4 bytes, little endian
275 prev_index = little_endian_to_int(s.read(4))
276 # use Script.parse to get the ScriptSig
277 script_sig = Script.parse(s)
278 # sequence is an integer in 4 bytes, little-endian
279 sequence = little_endian_to_int(s.read(4))
280 # return an instance of the class (see __init__ for args)
281 return cls(prev_tx, prev_index, script_sig, sequence)
282
283 def serialize(self):
284 '''Returns the byte serialization of the transaction input'''
285 # serialize prev_tx, little endian
286 result = self.prev_tx[::-1]
287 # serialize prev_index, 4 bytes, little endian
288 result += int_to_little_endian(self.prev_index, 4)
289 # serialize the script_sig
290 result += self.script_sig.serialize()
291 # serialize sequence, 4 bytes, little endian
292 result += int_to_little_endian(self.sequence, 4)
293 return result
294
295 def fetch_tx(self, testnet=False):
296 return TxFetcher.fetch(self.prev_tx.hex(), testnet=testnet)
297
298 def value(self, testnet=False):
299 '''Get the outpoint value by looking up the tx hash
300 Returns the amount in satoshi
301 '''
302 # use self.fetch_tx to get the transaction
303 tx = self.fetch_tx(testnet=testnet)
304 # get the output at self.prev_index
305 # return the amount property
306 return tx.tx_outs[self.prev_index].amount
307

Callers 4

sig_hashFunction · 0.90
sig_hashMethod · 0.70
test_input_valueMethod · 0.70
test_input_pubkeyMethod · 0.70

Calls

no outgoing calls

Tested by 2

test_input_valueMethod · 0.56
test_input_pubkeyMethod · 0.56