本文整理汇总了Python中BCDataStream.write方法的典型用法代码示例。如果您正苦于以下问题:Python BCDataStream.write方法的具体用法?Python BCDataStream.write怎么用?Python BCDataStream.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BCDataStream
的用法示例。
在下文中一共展示了BCDataStream.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scan_blocks
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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
示例2: search_blocks
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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'])
示例3: dump_block
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_block(datadir, db_env, block_hash):
""" Dump a block, given hexadecimal hash-- either the full hash
OR a short_hex version of the it.
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
n_blockindex = 0
key_prefix = "\x0ablockindex"
cursor = db.cursor()
(key, value) = cursor.set_range(key_prefix)
while key.startswith(key_prefix):
kds.clear()
kds.write(key)
vds.clear()
vds.write(value)
type = kds.read_string()
hash256 = kds.read_bytes(32)
hash_hex = long_hex(hash256[::-1])
block_data = _parse_block_index(vds)
if hash_hex.startswith(block_hash) or short_hex(hash256[::-1]).startswith(block_hash):
print "Block height: " + str(block_data["nHeight"])
_dump_block(datadir, block_data["nFile"], block_data["nBlockPos"], hash256, block_data["hashNext"])
(key, value) = cursor.next()
db.close()
示例4: read_block
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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
示例5: dump_keys
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_keys(db_env, addressStart, outputFileName):
db = DB(db_env)
try:
r = db.open("wallet.dat", "main", DB_BTREE, DB_THREAD|DB_RDONLY)
except DBError:
logging.error("Couldn't open addr.dat/main. Try quitting Bitcoin and running this again.")
return
cString = cStringIO.StringIO()
kds = BCDataStream()
vds = BCDataStream()
for (key, value) in db.items():
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
if type == "key":
publicKey = kds.read_bytes(kds.read_compact_size())
privateKey = vds.read_bytes(vds.read_compact_size())
address = public_key_to_bc_address(publicKey)
if address.startswith(addressStart):
privateKey58 = b58encode(privateKey)
cString.write('%s\n' % privateKey58)
print("\nPubKey hex: "+ long_hex(publicKey) + "\nPubKey base58: "+ b58encode(publicKey) + "\nAddress: " +
address + "\nPriKey hex: "+ long_hex(privateKey) + "\nPriKey base58: "+ privateKey58 + "\n")
outputText = cString.getvalue()
if outputText != '':
writeFileText(outputFileName, outputText)
db.close()
示例6: dump_block
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_block(datadir, db_env, block_hash, print_raw_tx=False, print_json=False):
""" Dump a block, given hexadecimal hash-- either the full hash
OR a short_hex version of the it.
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
n_blockindex = 0
key_prefix = "\x0ablockindex"
cursor = db.cursor()
(key, value) = cursor.set_range(key_prefix)
while key.startswith(key_prefix):
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
hash256 = kds.read_bytes(32)
hash_hex = long_hex(hash256[::-1])
block_data = _parse_block_index(vds)
if (hash_hex.startswith(block_hash) or short_hex(hash256[::-1]).startswith(block_hash)):
if print_json == False:
print "Block height: "+str(block_data['nHeight'])
_dump_block(datadir, block_data['nFile'], block_data['nBlockPos'], hash256, block_data['hashNext'], print_raw_tx=print_raw_tx)
else:
_dump_block(datadir, block_data['nFile'], block_data['nBlockPos'], hash256, block_data['hashNext'], print_json=print_json, do_print=False)
(key, value) = cursor.next()
db.close()
示例7: dump_addresses
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_addresses(db_env):
db = DB(db_env)
try:
r = db.open("addr.dat", "main", DB_BTREE, DB_THREAD|DB_RDONLY)
except DBError:
r = True
if r is not None:
logging.error("Couldn't open addr.dat/main. Try quitting Bitcoin and running this again.")
sys.exit(1)
kds = BCDataStream()
vds = BCDataStream()
for (key, value) in db.items():
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
if type == "addr":
d = parse_CAddress(vds)
print(deserialize_CAddress(d))
db.close()
示例8: dump_accounts
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_accounts(db_env):
db = open_wallet(db_env)
kds = BCDataStream()
vds = BCDataStream()
accounts = set()
for (key, value) in db.items():
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
if type == "acc":
accounts.add(kds.read_string())
elif type == "name":
accounts.add(vds.read_string())
elif type == "acentry":
accounts.add(kds.read_string())
# Note: don't need to add otheraccount, because moves are
# always double-entry
for name in sorted(accounts):
print(name)
db.close()
示例9: process_tx
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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)
示例10: check_block_chain
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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'])
示例11: sendbitcoin
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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: _read_tx
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def _read_tx(db, txhash):
kds = BCDataStream()
vds = BCDataStream()
key_prefix = "t"+txhash
cursor = db.iterator(prefix=key_prefix)
(key, value) = cursor.next()
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
kds.read_bytes(1)
hash256 = (kds.read_bytes(32))
tx_pos = _read_CDiskTxPos(vds)
return _dump_tx(datadir, hash256, tx_pos)
示例13: get_tx
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
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'}
示例14: _read_block
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def _read_block(db, blkhash):
key_prefix = "b"+(blkhash.decode('hex_codec')[::-1])
cursor = db.iterator(prefix=key_prefix)
(key, value) = cursor.next()
vds = BCDataStream()
vds.clear(); vds.write(value)
block_data = _parse_block_index(vds)
print block_data
if block_data['nStatus'] & 8 == False:
raise 'no block data, maybe data is downloaded?'
return
block = _dump_block(datadir, block_data['nFile'], block_data['nBlockPos'], blkhash)
block['hash256'] = blkhash
block['nHeight'] = block_data['nHeight']
return block
示例15: dump_transaction
# 需要导入模块: import BCDataStream [as 别名]
# 或者: from BCDataStream import write [as 别名]
def dump_transaction(datadir, db_env, tx_id):
""" Dump a transaction, given hexadecimal tx_id-- either the full ID
OR a short_hex version of the id.
"""
db = DB(db_env)
try:
r = db.open("blkindex.dat", "main", DB_BTREE, DB_THREAD | DB_RDONLY)
except DBError:
r = True
if r is not None:
logging.error("Couldn't open blkindex.dat/main. Try quitting any running Bitcoin apps.")
sys.exit(1)
kds = BCDataStream()
vds = BCDataStream()
n_tx = 0
n_blockindex = 0
key_prefix = "\x02tx" + (tx_id[-4:].decode("hex_codec")[::-1])
cursor = db.cursor()
(key, value) = cursor.set_range(key_prefix)
while key.startswith(key_prefix):
kds.clear()
kds.write(key)
vds.clear()
vds.write(value)
type = kds.read_string()
hash256 = kds.read_bytes(32)
hash_hex = long_hex(hash256[::-1])
version = vds.read_uint32()
tx_pos = _read_CDiskTxPos(vds)
if hash_hex.startswith(tx_id) or short_hex(hash256[::-1]).startswith(tx_id):
_dump_tx(datadir, hash256, tx_pos)
(key, value) = cursor.next()
db.close()