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()
Exemple #2
0
    def do_get_registers(self, args):
        args = split_args(args, 0, 1)
        if (args == None):
            return False

        if (len(args) == 0):
            output = ''
            for i, reg in enumerate(Register):
                value_hex = long_hex(self.simulator.get_register_value(reg))

                output += '{:<16}'.format(reg.name + ': ' + value_hex)
                if (i % 4 == 3):
                    output += '\n'

            print(output)
        else:
            # get the one passed in
            try:
                reg = Register[args[0]]
                value_hex = long_hex(self.simulator.get_register_value(reg))

                print(value_hex)
            except KeyError:
                print('[ERROR] unrecognized register ' + args[0])
                return False
Exemple #3
0
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
Exemple #4
0
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
def import_key(keyLine, db_dir, input_mode="b58", dryrun=False,verbose=False):
	if len(keyLine.strip()) == 0:
		return
	if input_mode == "b58":
		priv_bin = privkey_b58_bin(keyLine)
	elif input_mode == "b64":
		priv_bin = privkey_b64_bin(keyLine)
	elif input_mode == "bin":
		if len(keyLine) not in (32, 279):
			raise ValueError("Expected a key of 32 or 279 bytes")
		priv_bin = keyLine

	if len(priv_bin) == 32:
		# Get the full DER key
		priv_bin = priv_to_der(priv_bin)

	# The public key of a DER-encoded private key is just the last 65 bytes
	pub_bin = priv_bin[-65:]

	# Print out the key and address
	if verbose:
		print "Private key: %s" % util.long_hex(priv_bin)
		print "Public key:  %s" % util.long_hex(pub_bin)
	else:
		print "Private key: %s" % util.short_hex(priv_bin)
		print "Public key:  %s" % util.short_hex(pub_bin)
	addr = base58.public_key_to_bc_address(pub_bin)
	if addr == '':
		# This can happen if pycrypto is not installed, or if the RIPEMD160
		# hash is not available (it has been removed in the Debian/Ubuntu
		# version)
		print "Warning: Cannot calculate address; check pycrypto library"
	else:
		print "Address:	 %s" % addr

	# Data for wallet.update_wallet
	data = {
		'private_key': priv_bin,
		'public_key': pub_bin,
	}

	try:
		db_env = util.create_env(db_dir)
	except bsddb.db.DBNoSuchFileError:
		logging.error("Couldn't open " + db_dir)
		sys.exit(1)

	if not dryrun:
		db = wallet.open_wallet(db_env, writable=True)
		wallet.update_wallet(db, 'key', data)
		db.close()
Exemple #6
0
def import_key(keyLine, db_dir, input_mode="b58", dryrun=False, verbose=False):
    if len(keyLine.strip()) == 0:
        return
    if input_mode == "b58":
        priv_bin = privkey_b58_bin(keyLine)
    elif input_mode == "b64":
        priv_bin = privkey_b64_bin(keyLine)
    elif input_mode == "bin":
        if len(keyLine) not in (32, 279):
            raise ValueError("Expected a key of 32 or 279 bytes")
        priv_bin = keyLine

    if len(priv_bin) == 32:
        # Get the full DER key
        priv_bin = priv_to_der(priv_bin)

    # The public key of a DER-encoded private key is just the last 65 bytes
    pub_bin = priv_bin[-65:]

    # Print out the key and address
    if verbose:
        print "Private key: %s" % util.long_hex(priv_bin)
        print "Public key:  %s" % util.long_hex(pub_bin)
    else:
        print "Private key: %s" % util.short_hex(priv_bin)
        print "Public key:  %s" % util.short_hex(pub_bin)
    addr = base58.public_key_to_bc_address(pub_bin)
    if addr == '':
        # This can happen if pycrypto is not installed, or if the RIPEMD160
        # hash is not available (it has been removed in the Debian/Ubuntu
        # version)
        print "Warning: Cannot calculate address; check pycrypto library"
    else:
        print "Address:	 %s" % addr

    # Data for wallet.update_wallet
    data = {
        'private_key': priv_bin,
        'public_key': pub_bin,
    }

    try:
        db_env = util.create_env(db_dir)
    except bsddb.db.DBNoSuchFileError:
        logging.error("Couldn't open " + db_dir)
        sys.exit(1)

    if not dryrun:
        db = wallet.open_wallet(db_env, writable=True)
        wallet.update_wallet(db, 'key', data)
        db.close()
  def item_callback(type, d):
    if type == "tx":
      wallet_transactions.append( d )
      transaction_index[d['tx_id']] = d
    elif type == "key":
      owner_keys[public_key_to_bc_address(d['public_key'])] = d['private_key']
    elif type == "ckey":
      owner_keys[public_key_to_bc_address(d['public_key'])] = d['crypted_key']

    if not print_wallet:
      return
    if type == "tx":
      return
    elif type == "name":
      print("ADDRESS "+d['hash']+" : "+d['name'])
    elif type == "version":
      print("Version: %d"%(d['version'],))
    elif type == "setting":
      print(d['setting']+": "+str(d['value']))
    elif type == "key":
      print("PubKey "+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": PriKey "+ short_hex(d['private_key']))
    elif type == "wkey":
      print("WPubKey 0x"+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": WPriKey 0x"+ short_hex(d['crypted_key']))
      print(" Created: "+time.ctime(d['created'])+" Expires: "+time.ctime(d['expires'])+" Comment: "+d['comment'])
    elif type == "ckey":
      print("PubKey "+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": Encrypted PriKey "+ short_hex(d['crypted_key']))
    elif type == "mkey":
      print("Master Key %d"%(d['nID']) + ": 0x"+ short_hex(d['crypted_key']) +
            ", Salt: 0x"+ short_hex(d['salt']) +
            ". Passphrase hashed %d times with method %d with other parameters 0x"%(d['nDeriveIterations'], d['nDerivationMethod']) +
            long_hex(d['vchOtherDerivationParameters']))
    elif type == "defaultkey":
      print("Default Key: 0x"+ short_hex(d['key']) + " " + public_key_to_bc_address(d['key']))
    elif type == "pool":
      print("Change Pool key %d: %s (Time: %s)"% (d['n'], public_key_to_bc_address(d['public_key']), time.ctime(d['nTime'])))
    elif type == "acc":
      print("Account %s (current key: %s)"%(d['account'], public_key_to_bc_address(d['public_key'])))
    elif type == "acentry":
      print("Move '%s' %d (other: '%s', time: %s, entry %d) %s"%
            (d['account'], d['nCreditDebit'], d['otherAccount'], time.ctime(d['nTime']), d['n'], d['comment']))
    elif type == "bestblock":
      print deserialize_BlockLocator(d)
    elif type == "cscript":
      print("CScript: %s : %s"%(public_key_to_bc_address(d['scriptHash'], "\x01"), long_hex(d['script'])))
    else:
      print "Unknown key type: "+type
Exemple #8
0
  def item_callback(type, d):
    if type == "tx":
      wallet_transactions.append( d )
      transaction_index[d['tx_id']] = d
    elif type == "key":
      owner_keys[public_key_to_bc_address(d['public_key'])] = d['private_key']
    elif type == "ckey":
      owner_keys[public_key_to_bc_address(d['public_key'])] = d['crypted_key']

    if not print_wallet:
      return
    if type == "tx":
      return
    elif type == "name":
      print("ADDRESS "+d['hash']+" : "+d['name'])
    elif type == "version":
      print("Version: %d"%(d['version'],))
    elif type == "setting":
      print(d['setting']+": "+str(d['value']))
    elif type == "key":
      print("PubKey "+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": PriKey "+ short_hex(d['private_key']))
    elif type == "wkey":
      print("WPubKey 0x"+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": WPriKey 0x"+ short_hex(d['crypted_key']))
      print(" Created: "+time.ctime(d['created'])+" Expires: "+time.ctime(d['expires'])+" Comment: "+d['comment'])
    elif type == "ckey":
      print("PubKey "+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": Encrypted PriKey "+ long_hex(d['crypted_key'])) # short_hex()
    elif type == "mkey":
      print("Master Key %d"%(d['nID']) + ": 0x"+ short_hex(d['crypted_key']) +
            ", Salt: 0x"+ short_hex(d['salt']) +
            ". Passphrase hashed %d times with method %d with other parameters 0x"%(d['nDeriveIterations'], d['nDerivationMethod']) +
            long_hex(d['vchOtherDerivationParameters']))
    elif type == "defaultkey":
      print("Default Key: 0x"+ short_hex(d['key']) + " " + public_key_to_bc_address(d['key']))
    elif type == "pool":
      print("Change Pool key %d: %s (Time: %s)"% (d['n'], public_key_to_bc_address(d['public_key']), time.ctime(d['nTime'])))
    elif type == "acc":
      print("Account %s (current key: %s)"%(d['account'], public_key_to_bc_address(d['public_key'])))
    elif type == "acentry":
      print("Move '%s' %d (other: '%s', time: %s, entry %d) %s"%
            (d['account'], d['nCreditDebit'], d['otherAccount'], time.ctime(d['nTime']), d['n'], d['comment']))
    elif type == "bestblock":
      print deserialize_BlockLocator(d)
    elif type == "cscript":
      print("CScript: %s : %s"%(public_key_to_bc_address(d['scriptHash'], "\x01"), long_hex(d['script'])))
    else:
      print "Unknown key type: "+type
Exemple #9
0
def deserialize_TxIn(d, transaction_index=None, owner_keys=None):
  if d['prevout_hash'] == "\x00"*32:
    result = "TxIn: COIN GENERATED"
    result += " coinbase:"+d['scriptSig'].encode('hex_codec')
  elif transaction_index is not None and d['prevout_hash'] in transaction_index:
    p = transaction_index[d['prevout_hash']]['txOut'][d['prevout_n']]
    result = "TxIn: value: %f"%(p['value']/1.0e8,)
    result += " prev("+long_hex(d['prevout_hash'][::-1])+":"+str(d['prevout_n'])+")"
  else:
    result = "TxIn: prev("+long_hex(d['prevout_hash'][::-1])+":"+str(d['prevout_n'])+")"
    pk = extract_public_key(d['scriptSig'])
    result += " pubkey: "+pk
    result += " sig: "+decode_script(d['scriptSig'])
  if d['sequence'] < 0xffffffff: result += " sequence: "+hex(d['sequence'])
  return result
def deserialize_TxIn(d, transaction_index=None, owner_keys=None):
  if d['prevout_hash'] == "\x00"*32:
    result = "TxIn: COIN GENERATED"
    result += " coinbase:"+d['scriptSig'].encode('hex_codec')
  elif transaction_index is not None and d['prevout_hash'] in transaction_index:
    p = transaction_index[d['prevout_hash']]['txOut'][d['prevout_n']]
    result = "TxIn: value: %f"%(p['value']/1.0e8,)
    result += " prev("+long_hex(d['prevout_hash'][::-1])+":"+str(d['prevout_n'])+")"
  else:
    result = "TxIn: prev("+long_hex(d['prevout_hash'][::-1])+":"+str(d['prevout_n'])+")"
    pk = extract_public_key(d['scriptSig'])
    result += " pubkey: "+pk
    result += " sig: "+decode_script(d['scriptSig'])
  if d['sequence'] < 0xffffffff: result += " sequence: "+hex(d['sequence'])
  return result
def deserialize_TxIn(d, transaction_index=None, owner_keys=None):
    if d["prevout_hash"] == "\x00" * 32:
        result = "TxIn: COIN GENERATED"
        result += " coinbase:" + d["scriptSig"].encode("hex_codec")
    elif transaction_index is not None and d["prevout_hash"] in transaction_index:
        p = transaction_index[d["prevout_hash"]]["txOut"][d["prevout_n"]]
        result = "TxIn: value: %f" % (p["value"] / 1.0e8,)
        result += " prev(" + long_hex(d["prevout_hash"][::-1]) + ":" + str(d["prevout_n"]) + ")"
    else:
        result = "TxIn: prev(" + long_hex(d["prevout_hash"][::-1]) + ":" + str(d["prevout_n"]) + ")"
        pk = extract_public_key(d["scriptSig"])
        result += " pubkey: " + pk
        result += " sig: " + decode_script(d["scriptSig"])
    if d["sequence"] < 0xFFFFFFFF:
        result += " sequence: " + hex(d["sequence"])
    return result
Exemple #12
0
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()
Exemple #13
0
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()
Exemple #14
0
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()
Exemple #15
0
    def do_get_memory(self, args):
        args = split_args(args, 2, 0)
        if (args == None):
            return False

        memory = self.simulator.memory

        start = int(args[0], 0)
        length = int(args[1], 0)

        # round down to nearest multiple of 8 to keep alignment
        start -= start % 8

        for i in range(length):
            loc = start + i

            if (loc % 8 == 0):
                print(long_hex(loc), end='    ')

            ending = ' '
            if (i % 4 == 3):
                ending = '    '
            if (i % 8 == 7):
                ending = '\n'

            value_str = bytes(memory.get(Memory.Byte, loc)).hex()
            print(value_str, end=ending)
        print('')  # newline
def deserialize_TxIn(d, transaction_index=None, owner_keys=None):
  result = {}
  if d['prevout_hash'] == "\x00"*32:
    result['coinbase'] = d['scriptSig'].encode('hex_codec')
  else:
    result['txid'] = long_hex(d['prevout_hash'][::-1])
    result['vout'] = d['prevout_n']
  return result
Exemple #17
0
def deserialize_TxIn(d, transaction_index=None, owner_keys=None):
    result = {}
    if d['prevout_hash'] == "\x00" * 32:
        result['coinbase'] = d['scriptSig'].encode('hex_codec')
    else:
        result['txid'] = long_hex(d['prevout_hash'][::-1])
        result['vout'] = d['prevout_n']
    return result
Exemple #18
0
def dump_wallet(db_env, print_wallet, print_wallet_transactions,
                transaction_filter):
    db = open_wallet(db_env)

    wallet_transactions = []

    def item_callback(type, d):
        if type == "tx":
            wallet_transactions.append(d)
        elif print_wallet:
            if type == "name":
                print("ADDRESS " + d['hash'] + " : " + d['name'])
            elif type == "version":
                print("Version: %d" % (d['version'], ))
            elif type == "setting":
                print(d['setting'] + ": " + str(d['value']))
            elif type == "key":
                print("PubKey " + short_hex(d['public_key']) + " " +
                      public_key_to_bc_address(d['public_key']) + ": PriKey " +
                      short_hex(d['private_key']))
            elif type == "wkey":
                print("WPubKey 0x" + short_hex(d['public_key']) + " " +
                      public_key_to_bc_address(d['public_key']) +
                      ": WPriKey 0x" + short_hex(d['private_key']))
                print(" Created: " + time.ctime(d['created']) + " Expires: " +
                      time.ctime(d['expires']) + " Comment: " + d['comment'])
            elif type == "defaultkey":
                print("Default Key: 0x" + short_hex(d['key']) + " " +
                      public_key_to_bc_address(d['key']))
            elif type == "pool":
                print("Change Pool key %d: %s (Time: %s)" %
                      (d['n'], public_key_to_bc_address(
                          d['public_key']), time.ctime(d['nTime'])))
            elif type == "acc":
                print(
                    "Account %s (current key: %s)" %
                    (d['account'], public_key_to_bc_address(d['public_key'])))
            elif type == "acentry":
                print("Move '%s' %d (other: '%s', time: %s, entry %d) %s" %
                      (d['account'], d['nCreditDebit'], d['otherAccount'],
                       time.ctime(d['nTime']), d['n'], d['comment']))
            else:
                print "Unknown key type: " + type

    parse_wallet(db, item_callback)

    if print_wallet_transactions:
        sortfunc = lambda t1, t2: t1['timeReceived'] < t2['timeReceived']
        for d in sorted(wallet_transactions, cmp=sortfunc):
            tx_value = deserialize_WalletTx(d)
            if len(transaction_filter) > 0 and re.search(
                    transaction_filter, tx_value) is None:
                continue

            print("==WalletTransaction== " + long_hex(d['tx_id'][::-1]))
            print(tx_value)

    db.close()
Exemple #19
0
def decode_script(bytes):
  result = ''
  for (opcode, vch) in script_GetOp(bytes):
    if len(result) > 0: result += " "
    if opcode <= opcodes.OP_PUSHDATA4:
      result += "%d:"%(opcode,)
      result += long_hex(vch)
    else:
      result += script_GetOpName(opcode)
  return result
Exemple #20
0
def decode_script(bytes):
    result = ''
    for (opcode, vch) in script_GetOp(bytes):
        if len(result) > 0: result += " "
        if opcode <= opcodes.OP_PUSHDATA4:
            result += "%d:" % (opcode, )
            result += long_hex(vch)
        else:
            result += script_GetOpName(opcode)
    return result
Exemple #21
0
def dump_wallet(db_env, print_wallet, print_wallet_transactions, transaction_filter):
  db = open_wallet(db_env)

  wallet_transactions = []
  transaction_index = { }
  owner_keys = { }

  def item_callback(type, d):
    if type == "tx":
      wallet_transactions.append( d )
      transaction_index[d['tx_id']] = d
    elif type == "key":
      owner_keys[public_key_to_bc_address(d['public_key'])] = d['private_key']

    if not print_wallet:
      return
    if type == "tx":
      return
    elif type == "name":
      print("ADDRESS "+d['hash']+" : "+d['name'])
    elif type == "version":
      print("Version: %d"%(d['version'],))
    elif type == "setting":
      print(d['setting']+": "+str(d['value']))
    elif type == "key":
      print("PubKey "+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": PriKey "+ short_hex(d['private_key']))
    elif type == "wkey":
      print("WPubKey 0x"+ short_hex(d['public_key']) + " " + public_key_to_bc_address(d['public_key']) +
            ": WPriKey 0x"+ short_hex(d['private_key']))
      print(" Created: "+time.ctime(d['created'])+" Expires: "+time.ctime(d['expires'])+" Comment: "+d['comment'])
    elif type == "defaultkey":
      print("Default Key: 0x"+ short_hex(d['key']) + " " + public_key_to_bc_address(d['key']))
    elif type == "pool":
      print("Change Pool key %d: %s (Time: %s)"% (d['n'], public_key_to_bc_address(d['public_key']), time.ctime(d['nTime'])))
    elif type == "acc":
      print("Account %s (current key: %s)"%(d['account'], public_key_to_bc_address(d['public_key'])))
    elif type == "acentry":
      print("Move '%s' %d (other: '%s', time: %s, entry %d) %s"%
            (d['account'], d['nCreditDebit'], d['otherAccount'], time.ctime(d['nTime']), d['n'], d['comment']))
    else:
      print "Unknown key type: "+type

  parse_wallet(db, item_callback)

  if print_wallet_transactions:
    keyfunc = lambda i: i['timeReceived']
    for d in sorted(wallet_transactions, key=keyfunc):
      tx_value = deserialize_WalletTx(d, transaction_index, owner_keys)
      if len(transaction_filter) > 0 and re.search(transaction_filter, tx_value) is None: continue

      print("==WalletTransaction== "+long_hex(d['tx_id'][::-1]))
      print(tx_value)

  db.close()
Exemple #22
0
def deserialize_TxIn(d):
  if d['prevout_hash'] == "\x00"*32:
    result = "TxIn: COIN GENERATED"
    result += " coinbase:"+d['scriptSig'].encode('hex_codec')
  else:
    result = "TxIn: prev("+long_hex(d['prevout_hash'][::-1])+":"+str(d['prevout_n'])+")"
    pk = extract_public_key(d['scriptSig'])
    result += " pubkey: "+pk
    result += " sig: "+decode_script(d['scriptSig'])
  if d['sequence'] < 0xffffffff: result += " sequence: "+hex(d['sequence'])
  return result
Exemple #23
0
def deserialize_TxIn(d):
    if d['prevout_hash'] == "\x00" * 32:
        result = "TxIn: COIN GENERATED"
        result += " coinbase:" + d['scriptSig'].encode('hex_codec')
    else:
        result = "TxIn: prev(" + long_hex(d['prevout_hash'][::-1]) + ":" + str(
            d['prevout_n']) + ")"
        pk = extract_public_key(d['scriptSig'])
        result += " pubkey: " + pk
        result += " sig: " + decode_script(d['scriptSig'])
    if d['sequence'] < 0xffffffff: result += " sequence: " + hex(d['sequence'])
    return result
Exemple #24
0
def _dump_block(datadir,
                nFile,
                nBlockPos,
                hash256,
                hashNext,
                do_print=True,
                print_raw_tx=False,
                print_json=False):
    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, print_raw_tx)
    ds.close_file()
    blockfile.close()
    if do_print:
        print "BLOCK " + long_hex(hash256[::-1])
        print "Next block: " + long_hex(hashNext[::-1])
        print block_string
    elif print_json:
        import json
        print json.dumps({
            'version':
            d['version'],
            'previousblockhash':
            d['hashPrev'][::-1].encode('hex'),
            'transactions':
            [tx_hex['__data__'].encode('hex') for tx_hex in d['transactions']],
            'time':
            d['nTime'],
            'bits':
            hex(d['nBits']).lstrip("0x"),
            'nonce':
            d['nNonce']
        })

    return block_string
Exemple #25
0
def _dump_block(datadir, nFile, nBlockPos, hash256, hashNext, do_print=True, print_raw_tx=False, print_json=False):
  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, print_raw_tx)
  ds.close_file()
  blockfile.close()
  if do_print:
    print "BLOCK "+long_hex(hash256[::-1])
    print "Next block: "+long_hex(hashNext[::-1])
    print block_string
  elif print_json:
    import json
    print json.dumps({
                        'version': d['version'],
                        'previousblockhash': d['hashPrev'][::-1].encode('hex'),
                        'transactions' : [ tx_hex['__data__'].encode('hex') for tx_hex in d['transactions'] ],
                        'time' : d['nTime'],
                        'bits' : hex(d['nBits']).lstrip("0x"),
                        'nonce' : d['nNonce']
                      })

  return block_string
Exemple #26
0
def dump_wallet(db_env, print_wallet, print_wallet_transactions, transaction_filter):
    db = open_wallet(db_env)

    wallet_transactions = []
    transaction_index = {}
    owner_keys = {}

    def item_callback(type, d):
        if type == "tx":
            wallet_transactions.append(d)
            transaction_index[d["tx_id"]] = d
        elif type == "key":
            owner_keys[public_key_to_bc_address(d["public_key"])] = d["private_key"]
        elif type == "ckey":
            owner_keys[public_key_to_bc_address(d["public_key"])] = d["crypted_key"]

        if not print_wallet:
            return
        if type == "tx":
            return
        elif type == "name":
            print ("ADDRESS " + d["hash"] + " : " + d["name"])
        elif type == "version":
            print ("Version: %d" % (d["version"],))
        elif type == "setting":
            print (d["setting"] + ": " + str(d["value"]))
        elif type == "key":
            print (
                "PubKey "
                + short_hex(d["public_key"])
                + " "
                + public_key_to_bc_address(d["public_key"])
                + ": PriKey "
                + short_hex(d["private_key"])
            )
        elif type == "wkey":
            print (
                "WPubKey 0x"
                + short_hex(d["public_key"])
                + " "
                + public_key_to_bc_address(d["public_key"])
                + ": WPriKey 0x"
                + short_hex(d["crypted_key"])
            )
            print (
                " Created: "
                + time.ctime(d["created"])
                + " Expires: "
                + time.ctime(d["expires"])
                + " Comment: "
                + d["comment"]
            )
        elif type == "ckey":
            print (
                "PubKey "
                + short_hex(d["public_key"])
                + " "
                + public_key_to_bc_address(d["public_key"])
                + ": Encrypted PriKey "
                + short_hex(d["crypted_key"])
            )
        elif type == "mkey":
            print (
                "Master Key %d" % (d["nID"])
                + ": 0x"
                + short_hex(d["crypted_key"])
                + ", Salt: 0x"
                + short_hex(d["salt"])
                + ". Passphrase hashed %d times with method %d with other parameters 0x"
                % (d["nDeriveIterations"], d["nDerivationMethod"])
                + long_hex(d["vchOtherDerivationParameters"])
            )
        elif type == "defaultkey":
            print ("Default Key: 0x" + short_hex(d["key"]) + " " + public_key_to_bc_address(d["key"]))
        elif type == "pool":
            print (
                "Change Pool key %d: %s (Time: %s)"
                % (d["n"], public_key_to_bc_address(d["public_key"]), time.ctime(d["nTime"]))
            )
        elif type == "acc":
            print ("Account %s (current key: %s)" % (d["account"], public_key_to_bc_address(d["public_key"])))
        elif type == "acentry":
            print (
                "Move '%s' %d (other: '%s', time: %s, entry %d) %s"
                % (d["account"], d["nCreditDebit"], d["otherAccount"], time.ctime(d["nTime"]), d["n"], d["comment"])
            )
        elif type == "bestblock":
            print deserialize_BlockLocator(d)
        elif type == "cscript":
            print ("CScript: %s : %s" % (public_key_to_bc_address(d["scriptHash"], "\x01"), long_hex(d["script"])))
        else:
            print "Unknown key type: " + type

    parse_wallet(db, item_callback)

    if print_wallet_transactions:
        keyfunc = lambda i: i["timeReceived"]
        for d in sorted(wallet_transactions, key=keyfunc):
            tx_value = deserialize_WalletTx(d, transaction_index, owner_keys)
            if len(transaction_filter) > 0 and re.search(transaction_filter, tx_value) is None:
                continue

            print ("==WalletTransaction== " + long_hex(d["tx_id"][::-1]))
            print (tx_value)

    db.close()
Exemple #27
0
def dump_wallet(db_env, print_wallet, print_wallet_transactions,
                transaction_filter):
    db = open_wallet(db_env)

    wallet_transactions = []
    transaction_index = {}
    owner_keys = {}

    def item_callback(type, d):
        if type == "tx":
            wallet_transactions.append(d)
            transaction_index[d['tx_id']] = d
        elif type == "key":
            owner_keys[public_key_to_bc_address(
                d['public_key'])] = d['private_key']
        elif type == "ckey":
            owner_keys[public_key_to_bc_address(
                d['public_key'])] = d['crypted_key']

        if not print_wallet:
            return
        if type == "tx":
            return
        elif type == "name":
            print("ADDRESS " + d['hash'] + " : " + d['name'])
        elif type == "version":
            print("Version: %d" % (d['version'], ))
        elif type == "setting":
            print(d['setting'] + ": " + str(d['value']))
        elif type == "key":
            print("\nPubKey hex: " + long_hex(d['public_key']) +
                  "\nPubKey base58: " + b58encode(d['public_key']) +
                  "\nAddress: " + public_key_to_bc_address(d['public_key']) +
                  "\nPriKey hex: " + long_hex(d['private_key']) +
                  "\nPriKey base58: " + b58encode(d['private_key']) + "\n")
        elif type == "wkey":
            print("WPubKey 0x" + short_hex(d['public_key']) + " " +
                  public_key_to_bc_address(d['public_key']) + ": WPriKey 0x" +
                  short_hex(d['crypted_key']))
            print(" Created: " + time.ctime(d['created']) + " Expires: " +
                  time.ctime(d['expires']) + " Comment: " + d['comment'])
        elif type == "ckey":
            print("PubKey " + short_hex(d['public_key']) + " " +
                  public_key_to_bc_address(d['public_key']) +
                  ": Encrypted PriKey " + short_hex(d['crypted_key']))
        elif type == "mkey":
            print(
                "Master Key %d" % (d['nID']) + ": 0x" +
                short_hex(d['crypted_key']) + ", Salt: 0x" +
                short_hex(d['salt']) +
                ". Passphrase hashed %d times with method %d with other parameters 0x"
                % (d['nDeriveIterations'], d['nDerivationMethod']) +
                long_hex(d['vchOtherDerivationParameters']))
        elif type == "defaultkey":
            print("Default Key: 0x" + short_hex(d['key']) + " " +
                  public_key_to_bc_address(d['key']))
        elif type == "pool":
            print("Change Pool key %d: %s (Time: %s)" %
                  (d['n'], public_key_to_bc_address(
                      d['public_key']), time.ctime(d['nTime'])))
        elif type == "acc":
            print("Account %s (current key: %s)" %
                  (d['account'], public_key_to_bc_address(d['public_key'])))
        elif type == "acentry":
            print("Move '%s' %d (other: '%s', time: %s, entry %d) %s" %
                  (d['account'], d['nCreditDebit'], d['otherAccount'],
                   time.ctime(d['nTime']), d['n'], d['comment']))
        elif type == "bestblock":
            print deserialize_BlockLocator(d)
        else:
            print "Unknown key type: " + type

    parse_wallet(db, item_callback)

    if print_wallet_transactions:
        keyfunc = lambda i: i['timeReceived']
        for d in sorted(wallet_transactions, key=keyfunc):
            tx_value = deserialize_WalletTx(d, transaction_index, owner_keys)
            if len(transaction_filter) > 0 and re.search(
                    transaction_filter, tx_value) is None:
                continue

            print("==WalletTransaction== " + long_hex(d['tx_id'][::-1]))
            print(tx_value)

    db.close()