PPCoin: Release alert and checkpoint master public keys
[novacoin.git] / bitcointools / transaction.py
1 #
2 # Code for dumping a single transaction, given its ID
3 #
4
5 from bsddb.db import *
6 import logging
7 import os.path
8 import sys
9 import time
10
11 from BCDataStream import *
12 from base58 import public_key_to_bc_address
13 from util import short_hex
14 from deserialize import *
15
16 def _read_CDiskTxPos(stream):
17   n_file = stream.read_uint32()
18   n_block_pos = stream.read_uint32()
19   n_tx_pos = stream.read_uint32()
20   return (n_file, n_block_pos, n_tx_pos)
21
22 def _dump_tx(datadir, tx_hash, tx_pos):
23   blockfile = open(os.path.join(datadir, "blk%04d.dat"%(tx_pos[0],)), "rb")
24   ds = BCDataStream()
25   ds.map_file(blockfile, tx_pos[2])
26   d = parse_Transaction(ds)
27   print deserialize_Transaction(d)
28   ds.close_file()
29   blockfile.close()
30
31 def dump_transaction(datadir, db_env, tx_id):
32   """ Dump a transaction, given hexadecimal tx_id-- either the full ID
33       OR a short_hex version of the id.
34   """
35   db = DB(db_env)
36   try:
37     r = db.open("blkindex.dat", "main", DB_BTREE, DB_THREAD|DB_RDONLY)
38   except DBError:
39     r = True
40
41   if r is not None:
42     logging.error("Couldn't open blkindex.dat/main.  Try quitting any running Bitcoin apps.")
43     sys.exit(1)
44
45   kds = BCDataStream()
46   vds = BCDataStream()
47
48   n_tx = 0
49   n_blockindex = 0
50
51   key_prefix = "\x02tx"+(tx_id[-4:].decode('hex_codec')[::-1])
52   cursor = db.cursor()
53   (key, value) = cursor.set_range(key_prefix)
54
55   while key.startswith(key_prefix):
56     kds.clear(); kds.write(key)
57     vds.clear(); vds.write(value)
58
59     type = kds.read_string()
60     hash256 = (kds.read_bytes(32))
61     hash_hex = long_hex(hash256[::-1])
62     version = vds.read_uint32()
63     tx_pos = _read_CDiskTxPos(vds)
64     if (hash_hex.startswith(tx_id) or short_hex(hash256[::-1]).startswith(tx_id)):
65       _dump_tx(datadir, hash256, tx_pos)
66
67     (key, value) = cursor.next()
68
69   db.close()
70