| 401 | |
| 402 | |
| 403 | class TxIn: |
| 404 | |
| 405 | def __init__(self, prev_tx, prev_index, script_sig=None, sequence=0xffffffff): |
| 406 | self.prev_tx = prev_tx |
| 407 | self.prev_index = prev_index |
| 408 | if script_sig is None: |
| 409 | self.script_sig = Script() |
| 410 | else: |
| 411 | self.script_sig = script_sig |
| 412 | self.sequence = sequence |
| 413 | |
| 414 | def __repr__(self): |
| 415 | return '{}:{}'.format( |
| 416 | self.prev_tx.hex(), |
| 417 | self.prev_index, |
| 418 | ) |
| 419 | |
| 420 | @classmethod |
| 421 | def parse(cls, s): |
| 422 | '''Takes a byte stream and parses the tx_input at the start |
| 423 | return a TxIn object |
| 424 | ''' |
| 425 | # prev_tx is 32 bytes, little endian |
| 426 | prev_tx = s.read(32)[::-1] |
| 427 | # prev_index is an integer in 4 bytes, little endian |
| 428 | prev_index = little_endian_to_int(s.read(4)) |
| 429 | # use Script.parse to get the ScriptSig |
| 430 | script_sig = Script.parse(s) |
| 431 | # sequence is an integer in 4 bytes, little-endian |
| 432 | sequence = little_endian_to_int(s.read(4)) |
| 433 | # return an instance of the class (see __init__ for args) |
| 434 | return cls(prev_tx, prev_index, script_sig, sequence) |
| 435 | |
| 436 | def serialize(self): |
| 437 | '''Returns the byte serialization of the transaction input''' |
| 438 | # serialize prev_tx, little endian |
| 439 | result = self.prev_tx[::-1] |
| 440 | # serialize prev_index, 4 bytes, little endian |
| 441 | result += int_to_little_endian(self.prev_index, 4) |
| 442 | # serialize the script_sig |
| 443 | result += self.script_sig.serialize() |
| 444 | # serialize sequence, 4 bytes, little endian |
| 445 | result += int_to_little_endian(self.sequence, 4) |
| 446 | return result |
| 447 | |
| 448 | def fetch_tx(self, testnet=False): |
| 449 | return TxFetcher.fetch(self.prev_tx.hex(), testnet=testnet) |
| 450 | |
| 451 | def value(self, testnet=False): |
| 452 | '''Get the outpoint value by looking up the tx hash |
| 453 | Returns the amount in satoshi |
| 454 | ''' |
| 455 | # use self.fetch_tx to get the transaction |
| 456 | tx = self.fetch_tx(testnet=testnet) |
| 457 | # get the output at self.prev_index |
| 458 | # return the amount property |
| 459 | return tx.tx_outs[self.prev_index].amount |
| 460 |
no outgoing calls