本文整理汇总了Python中BCDataStream类的典型用法代码示例。如果您正苦于以下问题:Python BCDataStream类的具体用法?Python BCDataStream怎么用?Python BCDataStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BCDataStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dump_all_transactions
def dump_all_transactions(datadir, db_env):
""" Dump all transactions.
"""
blockfile = open(os.path.join(datadir, "blk%04d.dat"%(1,)), "rb")
block_datastream = BCDataStream()
block_datastream.map_file(blockfile, 0)
def for_each_block(block_data):
block_datastream.seek_file(block_data['nBlockPos'])
data = parse_Block(block_datastream)
block_datetime = datetime.fromtimestamp(data['nTime'])
dt = "%d-%02d-%02d-%02d-%02d-%02d"%(block_datetime.year, block_datetime.month, block_datetime.day, block_datetime.hour, block_datetime.minute, block_datetime.second)
for txn in data['transactions']:
try:
for txIn in txn['txIn']:
if txIn['prevout_hash'] == "\x00"*32:
print 'in\t' + txn['hash'] + '\tcoinbase\t' + dt
else:
pk = extract_public_key(txIn['scriptSig'])
print 'in\t' + txn['hash'] + '\t' + long_hex(txIn['prevout_hash'][::-1]) + '\t' + str(txIn['prevout_n']) + '\t' + pk + '\t' + dt
index = 0
for txOut in txn['txOut']:
pk = extract_public_key(txOut['scriptPubKey'])
print 'out\t' + txn['hash'] + '\t' + str(index) + '\t' + pk + '\t' + str(txOut['value']/1.0e8) + '\t' + dt
index += 1
except:
pass
return True
scan_blocks(datadir, db_env, for_each_block)
db_env.close()
示例2: read_block
def read_block(db_cursor, hash):
(key,value) = db_cursor.set_range("\x0ablockindex"+hash)
vds = BCDataStream()
vds.clear(); vds.write(value)
block_data = _parse_block_index(vds)
block_data['hash256'] = hash
return block_data
示例3: scan_blocks
def scan_blocks(datadir, db_env, callback_fn):
""" Scan through blocks, from last through genesis block,
calling callback_fn(block_data) for each.
callback_fn should return False if scanning should
stop, True if it should continue.
Returns last block_data scanned.
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
block_data = read_block(cursor, hashBestChain)
while callback_fn(block_data):
if block_data['nHeight'] == 0:
break;
block_data = read_block(cursor, block_data['hashPrev'])
return block_data
示例4: search_blocks
def search_blocks(datadir, db_env, pattern):
""" Dump a block given block number (== height, genesis block is 0)
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
block_data = read_block(cursor, hashBestChain)
if pattern == "NONSTANDARD_CSCRIPTS": # Hack to look for non-standard transactions
search_odd_scripts(datadir, cursor, block_data)
return
while True:
block_string = _dump_block(datadir, block_data['nFile'], block_data['nBlockPos'],
block_data['hash256'], block_data['hashNext'], False)
if re.search(pattern, block_string) is not None:
print "MATCH: Block height: "+str(block_data['nHeight'])
print block_string
if block_data['nHeight'] == 0:
break
block_data = read_block(cursor, block_data['hashPrev'])
示例5: check_block_chain
def check_block_chain(db_env):
""" Make sure hashPrev/hashNext pointers are consistent through block chain """
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
back_blocks = []
block_data = read_block(cursor, hashBestChain)
while block_data['nHeight'] > 0:
back_blocks.append( (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext']) )
block_data = read_block(cursor, block_data['hashPrev'])
back_blocks.append( (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext']) )
genesis_block = block_data
print("check block chain: genesis block merkle hash is: %s"%(block_data['hashMerkle'][::-1].encode('hex_codec')))
while block_data['hashNext'] != ('\0'*32):
forward = (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext'])
back = back_blocks.pop()
if forward != back:
print("Forward/back block mismatch at height %d!"%(block_data['nHeight'],))
print(" Forward: "+str(forward))
print(" Back: "+str(back))
block_data = read_block(cursor, block_data['hashNext'])
示例6: process_tx
def process_tx(self):
hash = self.tx
tx_broadcast = dict(hash=hash, value=0);
logging.info("processing tx hash: "+hash)
template = self.daemon.conn.proxy.getblocktemplate()
txns = template["transactions"];
txdata = None
for tx in txns:
if tx["hash"] == hash:
logging.info("tx found in mempool")
txdata = tx["data"]
break
if txdata:
raw = BCDataStream()
raw.write(txdata.decode('hex_codec'))
tx = parse_Transaction(raw)
for out in tx["txOut"]:
tx_broadcast["value"] += out["value"]
else:
logging.info("unable to find tx in mempool")
try:
tx = self.daemon.conn.gettransaction(hash)
tx = tx.transaction[0]
logging.debug(tx)
for out in tx["outpoints"]:
tx_broadcast["value"] += long(out["value"])
except bitcoinrpc.exceptions.InvalidAddressOrKey:
logging.info("tx not found in blockchain")
sys.exit(1)
date = datetime.datetime.fromtimestamp(tx["time"]).replace(tzinfo=tzlocal())
tx_broadcast["time"] = date.strftime('%Y-%m-%d %H:%M:%S%z')
tx_broadcast["value"] = format(tx_broadcast["value"] / 1e6,'.6f')
self.txnotify.post(tx_broadcast)
示例7: _dump_tx
def _dump_tx(datadir, tx_hash, tx_pos):
blockfile = open(os.path.join(datadir, "blk%04d.dat"%(tx_pos[0],)), "rb")
ds = BCDataStream()
ds.map_file(blockfile, tx_pos[2])
d = parse_Transaction(ds)
print deserialize_Transaction(d)
ds.close_file()
blockfile.close()
示例8: _dump_tx
def _dump_tx(datadir, tx_hash, tx_pos):
BLOCK_HEADER_SIZE = 80
blockfile = open(os.path.join(datadir, "blocks","blk%05d.dat"%(tx_pos[0],)), "rb")
ds = BCDataStream()
ds.map_file(blockfile, tx_pos[1]+BLOCK_HEADER_SIZE+tx_pos[2])
tx = parse_Transaction(ds)
tx['hash'] = tx_hash[::-1]
ds.close_file()
blockfile.close()
return tx
示例9: _dump_block
def _dump_block(datadir, nFile, nBlockPos, blkhash):
blockfile = open(os.path.join(datadir,"blocks","blk%05d.dat"%(nFile,)), "rb")
ds = BCDataStream()
ds.map_file(blockfile, nBlockPos)
block_start = ds.read_cursor
block = parse_Block(ds)
block_end = ds.read_cursor
block['blk_size'] = (block_end - block_start)
ds.close_file()
blockfile.close()
return block
示例10: main
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--datadir", dest="datadir", default=None,
help="Look for files here (defaults to bitcoin default)")
parser.add_option("--regex", dest="lookfor", default="/P2SH/",
help="Look for string/regular expression (default: %default)")
parser.add_option("--n", dest="howmany", default=999999, type="int",
help="Look back this many blocks (default: all)")
parser.add_option("--start", dest="start", default=0, type="int",
help="Skip this many blocks to start (default: 0)")
parser.add_option("--verbose", dest="verbose", default=False, action="store_true",
help="Print blocks that match")
(options, args) = parser.parse_args()
if options.datadir is None:
db_dir = determine_db_dir()
else:
db_dir = options.datadir
try:
db_env = create_env(db_dir)
except DBNoSuchFileError:
logging.error("Couldn't open " + db_dir)
sys.exit(1)
blockfile = open(os.path.join(db_dir, "blk%04d.dat"%(1,)), "rb")
block_datastream = BCDataStream()
block_datastream.map_file(blockfile, 0)
results = defaultdict(int)
def count_matches(block_data):
block_datastream.seek_file(block_data['nBlockPos'])
data = parse_Block(block_datastream)
coinbase = data['transactions'][0]
scriptSig = coinbase['txIn'][0]['scriptSig']
if results['skipped'] < options.start:
results['skipped'] += 1
else:
results['checked'] += 1
if re.search(options.lookfor, scriptSig) is not None:
results['matched'] += 1
if options.verbose: print("Block %d : %s"%(block_data['nHeight'], scriptSig.encode('string_escape')) )
results['searched'] += 1
return results['searched'] < options.howmany
scan_blocks(db_dir, db_env, count_matches)
db_env.close()
percent = (100.0*results['matched'])/results['checked']
print("Found %d matches in %d blocks (%.1f percent)"%(results['matched'], results['checked'], percent))
示例11: sendbitcoin
def sendbitcoin(address, amount=0, comment="", comment_to=""):
txid = sendtoaddress(address, amount, comment, comment_to)
if txid['result']:
_raw = getrawtransaction(txid['result'])
if _raw['result']:
ds = BCDataStream()
ds.write(binascii.unhexlify(_raw['result']))
_raw['result'] = deserialize.deserialize_TransactionRaw(deserialize.parse_Transaction(ds))
return _raw
else:
if txid['error']['code']==-4:
txid['error']['message']="Insufficient funds"
return txid
示例12: _dump_block
def _dump_block(datadir, nFile, nBlockPos, hash256, hashNext, do_print=True):
blockfile = open(os.path.join(datadir, "blk%04d.dat" % (nFile,)), "rb")
ds = BCDataStream()
ds.map_file(blockfile, nBlockPos)
d = parse_Block(ds)
block_string = deserialize_Block(d)
ds.close_file()
blockfile.close()
if do_print:
print "BLOCK " + long_hex(hash256[::-1])
print "Next block: " + long_hex(hashNext[::-1])
print block_string
return block_string
示例13: main
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--datadir", dest="datadir", default=None,
help="Look for files here (defaults to bitcoin default)")
(options, args) = parser.parse_args()
if options.datadir is None:
db_dir = determine_db_dir()
else:
db_dir = options.datadir
try:
db_env = create_env(db_dir)
except DBNoSuchFileError:
logging.error("Couldn't open " + db_dir)
sys.exit(1)
blockfile = open(os.path.join(db_dir, "blk%04d.dat"%(1,)), "rb")
block_datastream = BCDataStream()
block_datastream.map_file(blockfile, 0)
n_transactions = { }
v_transactions = { }
def gather_stats(block_data):
block_datastream.seek_file(block_data['nBlockPos'])
data = parse_Block(block_datastream)
block_date = date.fromtimestamp(data['nTime'])
key = "%d-%02d"%(block_date.year, block_date.month)
for txn in data['transactions'][1:]:
for txout in txn['txOut']:
if key in n_transactions:
n_transactions[key] += 1
v_transactions[key] += txout['value']
else:
n_transactions[key] = 1
v_transactions[key] = txout['value']
return True
scan_blocks(db_dir, db_env, gather_stats)
db_env.close()
keys = n_transactions.keys()
keys.sort()
for k in keys:
v = v_transactions[k]/1.0e8
print "%s,%d,%.2f"%(k, n_transactions[k], v)
示例14: main
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option(
"--datadir", dest="datadir", default=None, help="Look for files here (defaults to bitcoin default)"
)
(options, args) = parser.parse_args()
if options.datadir is None:
db_dir = determine_db_dir()
else:
db_dir = options.datadir
try:
db_env = create_env(db_dir)
except DBNoSuchFileError:
logging.error("Couldn't open " + db_dir)
sys.exit(1)
blockfile = open(os.path.join(db_dir, "blk%04d.dat" % (1,)), "rb")
block_datastream = BCDataStream()
block_datastream.map_file(blockfile, 0)
def gather(block_data):
block_datastream.seek_file(block_data["nBlockPos"])
data = parse_Block(block_datastream)
height = block_data["nHeight"]
coinbase = data["transactions"][0]
scriptSig = coinbase["txIn"][0]["scriptSig"]
if len(scriptSig) < 4:
return True
(n,) = struct.unpack_from("<I", scriptSig[0:4])
if n < 6 * 24 * 365.25 * 100: # 200 years of blocks:
print("%d: %d (%s)" % (height, n, approx_date(n)))
if ord(scriptSig[0]) == 0x03:
(n,) = struct.unpack_from("<I", scriptSig[1:4] + "\0")
if n < 6 * 24 * 365.25 * 100: # 200 years of blocks:
print("%d: PUSH %d (%s)" % (height, n, approx_date(n)))
return True
scan_blocks(db_dir, db_env, gather)
db_env.close()
示例15: get_tx
def get_tx(self,txhash,skip=0):
# validation txhash here
txhash = txhash.lower()
if not re.match(r'^[a-f0-9]{64}$',txhash):
return {"error" : "invalid transaction hash format"}
try:
print "trying ppcoind"
tx = self.conn.gettransaction(txhash)
confirmations = tx.confirmations;
tx = tx.transaction[0]
del tx['coindays']
tx['confirmations'] = confirmations
for out in tx["outpoints"]:
out["value"] = format(int(out["value"]) / 1e6,'.6f')
for inp in tx["inpoints"]:
inp["value"] = format(int(inp["value"]) / 1e6,'.6f')
tx['time'] = datetime.datetime.utcfromtimestamp(tx["time"]).strftime("%Y-%m-%d %H:%M:%S+0000")
return tx
except bitcoinrpc.exceptions.InvalidAddressOrKey:
print "checking elsewhere";
template = self.conn.proxy.getblocktemplate()
txns = template["transactions"];
txdata = None
for tx in txns:
if tx["hash"] == txhash:
txdata = tx["data"]
break
if txdata:
raw = BCDataStream()
raw.write(txdata.decode('hex_codec'))
tx = parse_Transaction(raw)
dtx = deserialize_Transaction_json(tx)
dtx["confirmations"] = 0
dtx["txid"] = txhash;
dtx['time'] = datetime.datetime.utcfromtimestamp(tx["time"]).strftime("%Y-%m-%d %H:%M:%S+0000")
#print dtx
for inp in dtx["inpoints"]:
old_tx = self.get_tx(inp["previoustx"])
#print old_tx
inp['value'] = old_tx['outpoints'][inp["previoustxindex"]]['value']
inp['scriptpubkey'] = old_tx['outpoints'][inp["previoustxindex"]]['scriptpubkey']
inp['peercoinaddress'] = old_tx['outpoints'][inp["previoustxindex"]]['peercoinaddress']
return dtx;
cherrypy.response.status = 500
return {'error' : 'tx not found'}