remove dangling whitespace
[stratum-mining.git] / lib / coinbasetx.py
1 import binascii
2 import halfnode
3 import struct
4 import util
5
6 class CoinbaseTransaction(halfnode.CTransaction):
7     '''Construct special transaction used for coinbase tx.
8     It also implements quick serialization using pre-cached
9     scriptSig template.'''
10
11     extranonce_type = '>Q'
12     extranonce_placeholder = struct.pack(extranonce_type, int('f000000ff111111f', 16))
13     extranonce_size = struct.calcsize(extranonce_type)
14
15     def __init__(self, timestamper, coinbaser, value, flags, height, data):
16         super(CoinbaseTransaction, self).__init__()
17
18         #self.extranonce = 0
19
20         if len(self.extranonce_placeholder) != self.extranonce_size:
21             raise Exception("Extranonce placeholder don't match expected length!")
22
23         tx_in = halfnode.CTxIn()
24         tx_in.prevout.hash = 0L
25         tx_in.prevout.n = 2**32-1
26         tx_in._scriptSig_template = (
27             util.ser_number(height) + binascii.unhexlify(flags) + util.ser_number(int(timestamper.time())) + \
28             chr(self.extranonce_size),
29             util.ser_string(coinbaser.get_coinbase_data() + data)
30         )
31
32         tx_in.scriptSig = tx_in._scriptSig_template[0] + self.extranonce_placeholder + tx_in._scriptSig_template[1]
33
34         tx_out = halfnode.CTxOut()
35         tx_out.nValue = value
36         tx_out.scriptPubKey = coinbaser.get_script_pubkey()
37
38         self.vin.append(tx_in)
39         self.vout.append(tx_out)
40
41         # Two parts of serialized coinbase, just put part1 + extranonce + part2 to have final serialized tx
42         self._serialized = super(CoinbaseTransaction, self).serialize().split(self.extranonce_placeholder)
43
44     def set_extranonce(self, extranonce):
45         if len(extranonce) != self.extranonce_size:
46             raise Exception("Incorrect extranonce size")
47
48         (part1, part2) = self.vin[0]._scriptSig_template
49         self.vin[0].scriptSig = part1 + extranonce + part2