Ejemplo n.º 1
0
    def test_demo_user_keys(self):
        sk_base58 = b"29oiwbqkhLGBuX5teL5d2vsiJ3EXk3dpyBiPwA7W9DJG"
        sk_decoded = base58.b58decode(sk_base58)
        hash = pyscrypt.hash(password=b"demouser",
                             salt=b"demouser",
                             N=1024,
                             r=1,
                             p=1,
                             dkLen=32)

        sk = base58.b58encode(hash)
        hex_sk = binascii.b2a_hex(hash)
        print('Secret Key:', sk, 'length: ', len(sk))
        self.assertEqual(sk_base58, sk)
        self.assertEqual(sk_decoded, hash)

        #print(sk)
        keypair = libnacl.public.SecretKey(hash)

        # 2ipFYsqXnrw4Mt2RUWzEQntAH1FEFB8R52rAT3eExn9S
        pk_base58 = base58.b58encode(keypair.pk)
        pk_decoded = base58.b58decode(pk_base58)

        self.assertEqual(pk_decoded, keypair.pk)
        print('Public Key:', pk_base58, 'length: ', len(pk_base58))

        print("XID: ", crypto.key_to_xid(keypair.pk))
Ejemplo n.º 2
0
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()
def invalid_values(valid_value):
    return [
        valid_value[:-2],
        valid_value[:-5],
        valid_value + '0',
        valid_value + base58.b58encode(b'0').decode("utf-8"),
        valid_value + base58.b58encode(b'somefake').decode("utf-8"),
        base58.b58encode(b'somefakevaluesomefakevalue').decode("utf-8")
    ]
def invalid_short_values(valid_value):
    return [
        valid_value[:1],
        valid_value[:2],
        valid_value[:5],
        '',
        base58.b58encode(b'1' * 10).decode("utf-8"),
        base58.b58encode(b'1' * 2).decode("utf-8")
    ]
def replica(replica):
    replica.node.requests = Requests()
    replica.isMaster = True
    replica.node.replica = replica
    replica.node.doDynamicValidation = functools.partial(randomDynamicValidation, replica.node)
    replica.node.applyReq = lambda self, *args, **kwargs: True
    replica.stateRootHash = lambda self, *args, **kwargs: base58.b58encode(randomString(32)).decode()
    replica.txnRootHash = lambda self, *args, **kwargs: base58.b58encode(randomString(32)).decode()
    replica.node.onBatchCreated = lambda self, *args, **kwargs: True
    replica.requestQueues[DOMAIN_LEDGER_ID] = OrderedSet()
    return replica
Ejemplo n.º 6
0
def ed25519_generate_key_pair():
    """
    Generate a new key pair and return the pair encoded in base58
    """
    sk, vk = ed25519.create_keypair()
    # Private key
    private_value_base58 = Ed25519SigningKey(base58.b58encode(sk.to_bytes())).to_ascii()

    # Public key
    public_value_compressed_base58 = Ed25519VerifyingKey(base58.b58encode(vk.to_bytes())).to_ascii()

    return private_value_base58, public_value_compressed_base58
Ejemplo n.º 7
0
    def to_dict(self):
        """
        Generate a dict of the fulfillment

        Returns:
            dict: representing the fulfillment
        """
        return {
            'type': Ed25519Sha256.TYPE_NAME,
            'public_key': base58.b58encode(self.public_key),
            'signature': base58.b58encode(self.signature) if self.signature else None
        }
Ejemplo n.º 8
0
    def test_generate_keypair(self):
        bob = libnacl.public.SecretKey()
        assert bob is not None

        self.assertEqual(len(bob.sk), 32)
        sk = base58.b58encode(bob.sk)
        pk = base58.b58encode(bob.pk)
        xid = crypto.key_to_xid(bob.pk)

        print("Public key: ", pk, ", len: ", len(pk))
        print("Secret key: ", sk, ", len: ", len(sk))
        print("XID: ", xid, ", len: ", len(xid))
Ejemplo n.º 9
0
    def doAttrDisclose(self, origin, target, txnId, key):
        box = libnacl.public.Box(b58decode(origin), b58decode(target))

        data = json.dumps({TXN_ID: txnId, SKEY: key})
        nonce, boxedMsg = box.encrypt(data.encode(), pack_nonce=False)

        op = {
            TARGET_NYM: target,
            TXN_TYPE: DISCLO,
            NONCE: b58encode(nonce).decode("utf-8"),
            DATA: b58encode(boxedMsg).decode("utf-8")
        }
        self.submit(op, identifier=origin)
Ejemplo n.º 10
0
	def encode_address(self, ip, port):
		ip = socket.inet_aton(ip)
		port = struct.pack("!H", port)
		data = ip + port
		h = base58.checksum(data)
		data += h[:4]
		return base58.b58encode(data)
Ejemplo n.º 11
0
def base58encoding(filename, type):
    image = open(filename)
    serializedImage = base58.b58encode(image.read())
    createTmp58File(serializedImage)
    getTempFilesSize(filename)
    #base58decoding(serializedImage)
    return serializedImage
def testNodeKeysChanged(looper, txnPoolNodeSet, tdir,
                        tconf, sdk_node_theta_added,
                        sdk_pool_handle,
                        allPluginsPath=None):
    new_steward_wallet, new_node = sdk_node_theta_added

    new_node.stop()
    looper.removeProdable(name=new_node.name)
    nodeHa, nodeCHa = HA(*new_node.nodestack.ha), HA(*new_node.clientstack.ha)
    sigseed = randomString(32).encode()
    verkey = base58.b58encode(SimpleSigner(seed=sigseed).naclSigner.verraw).decode("utf-8")
    sdk_change_node_keys(looper, new_node, new_steward_wallet, sdk_pool_handle, verkey)

    config_helper = PNodeConfigHelper(new_node.name, tconf, chroot=tdir)
    initNodeKeysForBothStacks(new_node.name, config_helper.keys_dir, sigseed,
                              override=True)

    logger.debug("{} starting with HAs {} {}".format(new_node, nodeHa, nodeCHa))

    node = TestNode(new_node.name,
                    config_helper=config_helper,
                    config=tconf,
                    ha=nodeHa, cliha=nodeCHa, pluginPaths=allPluginsPath)
    looper.add(node)
    # The last element of `txnPoolNodeSet` is the node Theta that was just
    # stopped
    txnPoolNodeSet[-1] = node

    looper.run(checkNodesConnected(txnPoolNodeSet))
    waitNodeDataEquality(looper, node, *txnPoolNodeSet[:-1])
    sdk_ensure_pool_functional(looper, txnPoolNodeSet, new_steward_wallet, sdk_pool_handle)
Ejemplo n.º 13
0
def hash_to_address_multichain(version, hash, checksum):
    """
    Format address the MultiChain way, with version bytes and checksum bytes.
    http://www.multichain.com/developers/address-format/

    :param version:
    :param hash:
    :param checksum:
    :return:
    """
    n = len(version)
    pos = 0
    i =0
    vh = ''
    while i<n:
        vh += version[i:i+1]
        vh += hash[pos:pos+5]
        i += 1
        pos += 5
    vh += hash[pos:]

    dh = double_sha256(vh)
    a = dh[:4]
    b = checksum
    new_checksum = ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
    vh += new_checksum[:4]
    return base58.b58encode(vh)
Ejemplo n.º 14
0
	def to_extended_key(self, include_prv=False):

		if not self.__testnet:
			version = 0x0488B21E if not include_prv else 0x0488ADE4
		else:
			version = 0x043587CF if not include_prv else 0x04358394

		version  = util.number_to_string(version, 2**32-1)
		depth    = util.number_to_string(self.__depth, 2**8-1)
		parentfp = self.parentfp()
		childnum = util.number_to_string(self.__childnum, 2**32-1)
		chaincode = self.__chain
		
		if include_prv:
			if self.__prvkey == None: raise Exception('private key unkown')
			data = '\x00' + util.number_to_string(self.__prvkey, SECP256k1.order)
		else:
			# compress point
			data = point_compress(self.point())
		import base58

		ekdata = ''.join([version, depth, parentfp, childnum, chaincode, data])
		
		checksum=hashlib.sha256(hashlib.sha256(ekdata).digest()).digest()[:4]

		return base58.b58encode(ekdata + checksum)
def create_bls_multi_sig(encoded_root_hash):
    pool_state_root_hash = base58.b58encode(b"somefakepoolroothashsomefakepoolroothash").decode("utf-8")
    txn_root_hash = base58.b58encode(b"somefaketxnroothashsomefaketxnroothash").decode("utf-8")
    ledger_id = 1
    timestamp = get_utc_epoch()

    value = MultiSignatureValue(ledger_id=ledger_id,
                                state_root_hash=encoded_root_hash,
                                pool_state_root_hash=pool_state_root_hash,
                                txn_root_hash=txn_root_hash,
                                timestamp=timestamp)

    sign = "1q" * 16
    participants = ["q" * 32, "w" * 32, "e" * 32, "r" * 32]

    return MultiSignature(sign, participants, value)
Ejemplo n.º 16
0
    def encode(data: Union[str, bytes]) -> str:
        """
        Return Base58 string from data

        :param data: Bytes or string data
        """
        return ensure_str(base58.b58encode(ensure_bytes(data)))
Ejemplo n.º 17
0
def key_to_fingerprint(key):
    """
    Fingerprint is used to uniquely identify an entity without exposing extra information.
    :param key: the public key
    :return:
    """
    #assert len(key) == 32

    sha256 = hashlib.sha256()
    sha256.update(key)
    key_hash = sha256.digest()

    #print('%r' % key_hash)

    #assert len(key_hash) == 32


    ripemd = hashlib.new('ripemd')
    ripemd.update(key_hash)
    key_hash = ripemd.digest()

    #assert len(key_hash) == 20

    sha256 = hashlib.sha256()
    sha256.update(FINGER_PREFIX)
    sha256.update(key_hash)
    checksum = sha256.digest()
    result = FINGER_PREFIX+key_hash+checksum[:4]
    return base58.b58encode(result)
Ejemplo n.º 18
0
def bip38_encrypt(privkey,passphrase):
    '''BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.'''
    privformat = get_privkey_format(privkey)
    if privformat in ['wif_compressed','hex_compressed']:
        compressed = True
        flagbyte = '\xe0'
        if privformat == 'wif_compressed':
            privkey = encode_privkey(privkey,'hex_compressed')
            privformat = get_privkey_format(privkey)
    if privformat in ['wif', 'hex']:
        compressed = False
        flagbyte = '\xc0'
    if privformat == 'wif':
        privkey = encode_privkey(privkey,'hex')
        privformat = get_privkey_format(privkey)
    pubkey = privtopub(privkey)
    addr = pubtoaddr(pubkey)
    addresshash = hashlib.sha256(hashlib.sha256(addr).digest()).digest()[0:4]
    key = scrypt.hash(passphrase, addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    aes = AES.new(derivedhalf2)
    encryptedhalf1 = aes.encrypt(binascii.unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(binascii.hexlify(derivedhalf1[0:16]), 16))))
    encryptedhalf2 = aes.encrypt(binascii.unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(binascii.hexlify(derivedhalf1[16:32]), 16))))
    encrypted_privkey = ('\x01\x42' + flagbyte + addresshash + encryptedhalf1 + encryptedhalf2)
    encrypted_privkey += hashlib.sha256(hashlib.sha256(encrypted_privkey).digest()).digest()[:4] # b58check for encrypted privkey
    encrypted_privkey = base58.b58encode(encrypted_privkey)
    return encrypted_privkey
Ejemplo n.º 19
0
    def process_response(self, request, response):
        """
        If we have multiple Set-Cookies, combine them into a single ZappaCookie.
        Returns the modified HTTP Response.

        """

        if not response.cookies.keys():
            return response

        # If setting cookie on a 301/2,
        # return 200 and replace the content with a javascript redirector
        if response.status_code != 200 and response.has_header('Location'):
            location = response.get('Location')
            response.content = REDIRECT_HTML.replace('REDIRECT_ME', location)
            response.status_code = 200

        pack = {}
        for key in response.cookies.keys():
            pack[key] = response.cookies[key].value
            del(response.cookies[key])

        pack_s = json.dumps(pack)
        encoded = base58.b58encode(pack_s)

        response.set_cookie('zappa', encoded)

        return response
Ejemplo n.º 20
0
def test_round_trips():
    possible_bytes = [b'\x00', b'\x01', b'\x10', b'\xff']
    for length in range(0, 5):
        for bytes_to_test in product(possible_bytes, repeat=length):
            bytes_in = b''.join(bytes_to_test)
            bytes_out = b58decode(b58encode(bytes_in))
            assert_that(bytes_in, equal_to(bytes_out))
Ejemplo n.º 21
0
 def encode(private_value):
     """
     Encode the decimal number private_value to base58
     """
     private_value_hex = bitcoin.encode_privkey(private_value, "hex")
     private_value_base58 = base58.b58encode(bytes.fromhex(private_value_hex))
     return private_value_base58
Ejemplo n.º 22
0
        def injecting_start_response(status, headers, exc_info=None):
            # Iterate through the headers looking for Set-Cookie
            updates = False
            for idx, (header, value)  in enumerate(headers):
                if header == 'Set-Cookie':
                    cookie = parse_cookie(value)
                    if 'zappa' in cookie:
                        # We found a header in the response object that sets
                        # zappa as a cookie. Delete it.
                        del(headers[idx])
                        del(cookie['zappa'])
                        print 'deleted zappa set-cooke header'
                        print 'remaining cookie', cookie
                    if cookie:
                        updates = True
                        request_cookies.update(cookie)
                        print 'setting cookie', cookie

            # Encode cookies into Zappa cookie
            if updates and request_cookies:
                final_cookies = ["{cookie}={value}".format(cookie=k, value=v) for k, v in request_cookies.items()]
                encoded = base58.b58encode(';'.join(final_cookies))
                headers.append(('Set-Cookie', dump_cookie('zappa', value=encoded)))

            return start_response(status, headers, exc_info)
Ejemplo n.º 23
0
def pubkey_to_addr(pubkey, net=BC):
    # Addresses:
    # https://en.bitcoin.it/wiki/Protocol_documentation
    keyhash = net.pubkeyprefix + ripesha(pubkey).digest()
    checksum = shasha(keyhash).digest()[:4]
    address = b58encode(keyhash + checksum)
    return address
Ejemplo n.º 24
0
 def encode(public_value_x, public_value_y):
     """
     Encode the public key represented by the decimal values x and y to base58
     """
     public_value_compressed_hex = bitcoin.encode_pubkey([public_value_x, public_value_y], "hex_compressed")
     public_value_compressed_base58 = base58.b58encode(bytes.fromhex(public_value_compressed_hex))
     return public_value_compressed_base58
def private_key_to_human(private_key, advanced):
    """
    this function takes a 32 byte ed25519 private key in binary form and
    returns a string with a human readable private key according to this spec:
    https://github.com/FactomProject/FactomDocs/blob/master/factomDataStructureDetails.md#factoid-private-keys
    For example.  a binary private key passed like this :
    12fab77add10bcabe1b62b3fe8b167e966e4beee38ccf0062fdd207b5906c841
    would return this string:
    Fs1Ts7PsKMwo4ftCYxQJ3rW4pLiRBXyGEjMrxtHycLu52aDgKGEy

    The advanced parameter set to true displays technical internal data
    """

    hex_seed = private_key.encode('hex')
    private_key_prefix = factoid_secret_key_prefix + hex_seed

    if advanced == True:
        print "Private key with prefix:   " + private_key_prefix

    digest = hashlib.sha256(hashlib.sha256(private_key_prefix.decode("hex")).digest()).digest()
    if advanced == True:
        print "Private key hash: " + digest.encode('hex')
    checksummed_private_key = private_key_prefix + digest[:4].encode('hex')
    if advanced == True:
        print "Private key with checksum: " + checksummed_private_key
    human_privkey =  base58.b58encode(checksummed_private_key.decode("hex"))
    if advanced == True:
        print "Human readable private key: " + human_privkey
    return human_privkey
Ejemplo n.º 26
0
def sdk_change_bls_key(looper, txnPoolNodeSet,
                       node,
                       sdk_pool_handle,
                       sdk_wallet_steward,
                       add_wrong=False,
                       new_bls=None):
    new_blspk = init_bls_keys(node.keys_dir, node.name)
    key_in_txn = new_bls or new_blspk \
        if not add_wrong \
        else base58.b58encode(randomString(128).encode())
    node_dest = hexToFriendly(node.nodestack.verhex)
    sdk_send_update_node(looper, sdk_wallet_steward,
                         sdk_pool_handle,
                         node_dest, node.name,
                         None, None,
                         None, None,
                         bls_key=key_in_txn,
                         services=None)
    poolSetExceptOne = list(txnPoolNodeSet)
    poolSetExceptOne.remove(node)
    waitNodeDataEquality(looper, node, *poolSetExceptOne)
    sdk_pool_refresh(looper, sdk_pool_handle)
    sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_steward,
                    alias=randomString(5))
    ensure_all_nodes_have_same_data(looper, txnPoolNodeSet)
    return new_blspk
def pre_prepare_with_incorrect_bls_pool_ledger(multi_signature):
    multi_signature.signature = base58.b58encode(b"somefakesignaturesomefakesignaturesomefakesignature").decode("utf-8")
    params = create_pre_prepare_params(state_root=multi_signature.value.state_root_hash,
                                       pool_state_root=multi_signature.value.pool_state_root_hash,
                                       bls_multi_sig=multi_signature,
                                       ledger_id=POOL_LEDGER_ID)
    return PrePrepare(*params)
Ejemplo n.º 28
0
def _fulfillment_to_details(fulfillment):
    """
    Encode a fulfillment as a details dictionary

    Args:
        fulfillment: Crypto-conditions Fulfillment object
    """

    if fulfillment.type_name == 'ed25519-sha-256':
        return {
            'type': 'ed25519-sha-256',
            'public_key': base58.b58encode(fulfillment.public_key),
        }

    if fulfillment.type_name == 'threshold-sha-256':
        subconditions = [
            _fulfillment_to_details(cond['body'])
            for cond in fulfillment.subconditions
        ]
        return {
            'type': 'threshold-sha-256',
            'threshold': fulfillment.threshold,
            'subconditions': subconditions,
        }

    raise UnsupportedTypeError(fulfillment.type_name)
Ejemplo n.º 29
0
def from_hash160(h160, currency='btc', typ='pub', version=None):
    """Create crypto currency address from hash160 digest.

    :h160: string, digest hash160 to create address from.
    :currency: string, three letter code for the currency
    :typ: string, type of address 'priv' for private addresses
                  or 'pub' for public addresses
    :version: int, prefix for any other currency,
                   if set params currency and typ are ignored
    :returns: string, Base58 encoded address

    """
    if all(c in string.hexdigits for c in h160):
        h160 = h160.decode('hex')

    currency = currency.lower()

    if currency not in versions.keys():
        raise Exception('Currency %s is unknown.' % currency)

    if version is None:
        version = versions[currency][typ]

    h160 = chr(version) + h160
    h = dhash(h160)
    addr = h160 + h[0:4]

    pad = 0
    for c in h160:
        if c == chr(0):
            pad += 1
        else:
            break

    return base58.alphabet[0] * pad + base58.b58encode(addr)
Ejemplo n.º 30
0
def client1Signer():
    seed = b'client1Signer secret key........'
    signer = DidSigner(seed=seed)
    testable_verkey = friendlyToRaw(signer.identifier)
    testable_verkey += friendlyToRaw(signer.verkey[1:])
    testable_verkey = base58.b58encode(testable_verkey)
    assert testable_verkey == '6JvpZp2haQgisbXEXE9NE6n3Tuv77MZb5HdF9jS5qY8m'
    return signer
Ejemplo n.º 31
0
print("---------------------------------------")

output = hashHex('sha256', publicKeyHex)
print("apply sha-256 to public key: ", output)

output = hashHex('ripemd160', output)
print("apply ripemd160 to sha-256 applied public key: ", output)

output = "00" + output
print("add network bytes to ripemd160 applied hash - extended ripemd160: ",
      output, "\n")

print("checksum calculation")

checksum = hashHex('sha256', output)
print("apply sha-256 to extended ripemd160: ", checksum)

checksum = hashHex('sha256', checksum)
print("apply second time sha-256: ", checksum)

checksum = checksum[0:8]
print("extract first 8 characters as checksum: ", checksum)

address = output + checksum
print("append checksum to extended ripemd160", address)

print("---------------------------------------")

import base58
address = base58.b58encode(hexStringToByte(address))
print("this is your bitcoin address:", str(address)[2:len(address) - 2])
#create p2sh address

#1 OP_ADD[0x93] 01 0x63 OP_EQUAL[0x87]
#OP_CHECKSIGVERIFY [0xad]
#OP_1              [0x51]
#OP_MUL            [0x95]
#0xAD OP_1 OP_1 OP_MUL

redeemScript = 'ad515195'

#2 Generate scriptPubKey as OP_HASH160 hash160(redeemScript) OP_EQUAL
data = hash160(redeemScript.decode('hex')).encode('hex')
print data
scriptPubKey = 'a914' + data + '87'

version = '05'  #mainnet
version = 'c4'  #testnet
data = version + data

#print EncodeBase58Check(data.decode('hex'))
#3 Generate address with 0x05 prefix and double SHA256 hash checksum(=4bytes)
checksum = dhash256(data.decode('hex'))
checksum = checksum.encode('hex')[0:8]
addressHash = data + checksum

#4 bash58encode
address = b58encode(addressHash.decode('hex'))
print address

#2My2ApqGcoNXYceZC4d7fipBu4GodkbefHD
Ejemplo n.º 33
0
def generate_state_root():
    return base58.b58encode(os.urandom(32)).decode("utf-8")
Ejemplo n.º 34
0
# there is a method to output the curve coordinates in decimal
# outputs coordinates: the (x,y) point on the curve
print(public_key.public_numbers()) 
x_coord = public_key.public_numbers()._x
# convert to hex
pub_key_hex = hex(x_coord)
# strip the first two characters signifying python hex number
pub_key_hex = pub_key_hex[2:]
# append the prefix 03 indicating that the y-value was odd
# with this code, half the address should not validate
pub_key_hex = '03'+pub_key_hex

import hashlib
# double-hashed first as sha256, then as ripemd160 
temp = hashlib.sha256(pub_key_hex.encode())
pub_key_hash = hashlib.new('ripemd160',temp.digest()).digest()

# prefix a zero byte for a bitcoin address
pub_key_hash = bytes.fromhex('00')+pub_key_hash

# double sha256 hash and take the first 4 bytes as a checksum
dubhash = hashlib.sha256(hashlib.sha256(pub_key_hash).digest()).digest()
checksum = dubhash[:4]
pub_key_hash = pub_key_hash + checksum

# now convert to base58 encoding
# may have to >>> pip install base58
import base58
b58 = base58.b58encode(pub_key_hash)
btc_address = b58.decode()
print(btc_address)
Ejemplo n.º 35
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

#facilisimoDeveloper: roberto

import pywaves as pw
import base58

pw.setChain(chain='L')
newAddress = pw.Address()

encodeSeed = base58.b58encode(newAddress.seed.encode('utf-8'))

print "---Wallet encoded seed---"
print encodeSeed
print ""
print "---data Address---"
print newAddress
Ejemplo n.º 36
0
 def __verkey(self):
     return base58.b58encode(self._node.nodestack.verKey).decode("utf-8")
# Front end settings
bind_address = "127.0.0.1"
bind_port = 6771

db_url = "sqlite:///gateway.db"

waves_api_url = "http://127.0.0.1:6869"
waves_api_key = "evik904i5v9mgoupgsnio"

testnet = True

gateway_address = "3N3qmHa1MBo3ZjDYJZbHNezY4RfhtTFxjXG"
gateway_private_key = b'\x88rz\x037{\xfb\xa1\xb3e\\^\xcb\x97\x8d\xa1q\xe0$\xaa\xd7"\xeeI\xff\xf9!Jt~pa'
import curve25519, base58
gateway_public_key = curve25519.public(gateway_private_key)
print("Gateway's public key:", gateway_public_key, base58.b58encode(gateway_public_key))

default_fee = 100000

#currencies = {"3k2qVm2BSGvjCXNBGdFwq5mYSrd4LJmVgfBGro4qRQ1W": "mock_bank_usd"}
currencies = {"CcvuevJVhadmRipPQgWkGDreUcdnRGWjBJ2ey7mzop9g": "dogecoin"}

required_confirmations = 0

start_from_block = 3961
rescan_blockchain = False

import logging
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
Ejemplo n.º 38
0
def id_b58_encode(peer_id):
    """
    return a b58-encoded string
    """
    #pylint: disable=protected-access
    return base58.b58encode(peer_id._id_str).decode()
Ejemplo n.º 39
0
 def pretty(self):
     return base58.b58encode(self._id_str).decode()
Ejemplo n.º 40
0
def hash_to_address(version, hash):
    vh = version + hash
    return base58.b58encode(vh + double_sha256(vh)[:4])
Ejemplo n.º 41
0
 def generate_new_id(self) -> None:
     """Randomly generate an ID representing this report's execution."""
     self.report_id = base58.b58encode(uuid.uuid4().bytes).decode()
Ejemplo n.º 42
0
                       password=conf.db.pwd,
                       database=conf.db.db,
                       port=conf.db.port)

cursor = conn.cursor()

i = 0
while (True):
    try:
        sql = "SELECT * FROM incoming ORDER BY id ASC LIMIT 1"
        cursor.execute(sql, [])
        data = cursor.fetchall()
        if not data:
            time.sleep(10)
            continue
        address = base58.b58encode(data[0][1])

        # was stored and is saved without version bit
        public = [address]
        cursor.execute("INSERT INTO public(address) values(%s)", public)

        archive = [cursor.lastrowid, data[0][2]]
        cursor.execute("INSERT INTO archive(public_id, pkey) values(%s,%s)",
                       archive)

        cursor.execute("DELETE FROM incoming WHERE id = %s", [data[0][0]])
        conn.commit()
        i += 1
        print(str(i))
    except MySQLdb.Error, e:
        print e[0], e[1]
Ejemplo n.º 43
0
def Encode(text):
    text = text.encode('UTF-8')

    return base58.b58encode(text)
Ejemplo n.º 44
0
def btc_key_to_wif(private_key):
    fullkey = '80' + binascii.hexlify(bytes.fromhex(private_key)).decode()
    sha256a = hashlib.sha256(binascii.unhexlify(fullkey)).hexdigest()
    sha256b = hashlib.sha256(binascii.unhexlify(sha256a)).hexdigest()
    WIF = base58.b58encode(binascii.unhexlify(fullkey + sha256b[:8]))
    return WIF.decode()
Ejemplo n.º 45
0
    def _acquire_access_token(self):

        self._token = os.environ.get('AVA_ACCESS_TOKEN',
                                     base58.b58encode(os.urandom(16)))
Ejemplo n.º 46
0
if args.path is None:
    args.path = "48'/13'/0'/0'/0'"

donglePath = parse_bip32_path(args.path)
apdu = "D4020001".decode('hex') + chr(len(donglePath) + 1) + chr(
    len(donglePath) / 4) + donglePath

dongle = getDongle(True)
result = dongle.exchange(bytes(apdu))
offset = 1 + result[0]
address = result[offset + 1:offset + 1 + result[offset]]

public_key = result[1:1 + result[0]]
head = 0x03 if (public_key[64] & 0x01) == 1 else 0x02
public_key_compressed = bytearray([head]) + public_key[1:33]

print "           Public key " + str(public_key).encode('hex')
print "Public key compressed " + str(public_key_compressed).encode('hex')

ripemd = hashlib.new('ripemd160')
ripemd.update(public_key_compressed)
check = ripemd.digest()[:4]

buff = public_key_compressed + check
print "Calculated from public key: Address STM" + b58encode(str(buff))
print "      Received from ledger: Address " + str(address)

apdu = "D4020101".decode('hex') + chr(len(donglePath) + 1) + chr(
    len(donglePath) / 4) + donglePath
result = dongle.exchange(bytes(apdu))
Ejemplo n.º 47
0
    def __node_info(self):
        ledger_statuses = {}
        waiting_cp = {}
        num_txns_in_catchup = {}
        last_txn_3PC_keys = {}
        committed_ledger_root_hashes = {}
        uncommited_ledger_root_hashes = {}
        uncommitted_ledger_txns = {}
        committed_state_root_hashes = {}
        uncommitted_state_root_hashes = {}
        for idx, linfo in self._node.ledgerManager.ledgerRegistry.items():
            ledger_statuses[idx] = self._prepare_for_json(linfo.state.name)
            waiting_cp[idx] = self._prepare_for_json(linfo.catchUpTill)
            num_txns_in_catchup[idx] = self._prepare_for_json(
                linfo.num_txns_caught_up)
            last_txn_3PC_keys[idx] = self._prepare_for_json(
                linfo.last_txn_3PC_key)
            if linfo.ledger.uncommittedRootHash:
                uncommited_ledger_root_hashes[idx] = self._prepare_for_json(
                    base58.b58encode(linfo.ledger.uncommittedRootHash))
            txns = {"Count": len(linfo.ledger.uncommittedTxns)}
            if len(linfo.ledger.uncommittedTxns) > 0:
                txns["First_txn"] = self._prepare_for_json(
                    linfo.ledger.uncommittedTxns[0])
                txns["Last_txn"] = self._prepare_for_json(
                    linfo.ledger.uncommittedTxns[-1])
            uncommitted_ledger_txns[idx] = txns
            if linfo.ledger.tree.root_hash:
                committed_ledger_root_hashes[idx] = self._prepare_for_json(
                    base58.b58encode(linfo.ledger.tree.root_hash))
        for l_id, req_handler in self._node.ledger_to_req_handler.items():
            committed_state_root_hashes[l_id] = self._prepare_for_json(
                base58.b58encode(req_handler.state.committedHeadHash))
            uncommitted_state_root_hashes[l_id] = self._prepare_for_json(
                base58.b58encode(req_handler.state.headHash))

        return {
            "Node_info": {
                "Name":
                self._prepare_for_json(self.__alias),
                "Mode":
                self._prepare_for_json(self._node.mode.name),
                "Client_port":
                self._prepare_for_json(self.__client_port),
                "Client_protocol":
                self._prepare_for_json(ZMQ_NETWORK_PROTOCOL),
                "Node_port":
                self._prepare_for_json(self.__node_port),
                "Node_protocol":
                self._prepare_for_json(ZMQ_NETWORK_PROTOCOL),
                "did":
                self._prepare_for_json(self.__did),
                'verkey':
                self._prepare_for_json(self.__verkey),
                "Metrics":
                self._prepare_for_json(self._get_node_metrics()),
                "Committed_ledger_root_hashes":
                self._prepare_for_json(committed_ledger_root_hashes),
                "Committed_state_root_hashes":
                self._prepare_for_json(committed_state_root_hashes),
                "Uncommitted_ledger_root_hashes":
                self._prepare_for_json(uncommited_ledger_root_hashes),
                "Uncommitted_ledger_txns":
                self._prepare_for_json(uncommitted_ledger_txns),
                "Uncommitted_state_root_hashes":
                self._prepare_for_json(uncommitted_state_root_hashes),
                "View_change_status": {
                    "View_No":
                    self._prepare_for_json(self._node.viewNo),
                    "VC_in_progress":
                    self._prepare_for_json(
                        self._node.view_changer.view_change_in_progress),
                    "Last_view_change_started_at":
                    self._prepare_for_json(self.__get_start_vc_ts()),
                    "Last_complete_view_no":
                    self._prepare_for_json(
                        self._node.view_changer.last_completed_view_no),
                    "IC_queue":
                    self._prepare_for_json(self._get_ic_queue()),
                    "VCDone_queue":
                    self._prepare_for_json(
                        self._node.view_changer._view_change_done)
                },
                "Catchup_status": {
                    "Ledger_statuses":
                    self._prepare_for_json(ledger_statuses),
                    "Received_LedgerStatus":
                    "",
                    "Waiting_consistency_proof_msgs":
                    self._prepare_for_json(waiting_cp),
                    "Number_txns_in_catchup":
                    self._prepare_for_json(num_txns_in_catchup),
                    "Last_txn_3PC_keys":
                    self._prepare_for_json(last_txn_3PC_keys),
                },
                "Count_of_replicas":
                self._prepare_for_json(len(self._node.replicas)),
                "Replicas_status":
                self._prepare_for_json(self.__replicas_status),
                "Pool_ledger_size":
                self._prepare_for_json(self._get_pool_ledger_size()),
                "Domain_ledger_size":
                self._prepare_for_json(self._get_domain_ledger_size()),
                "Config_ledger_size":
                self._prepare_for_json(self._get_config_ledger_size()),
            }
        }
Ejemplo n.º 48
0
def rand_str(length):
    res = ''
    lower = 'abcdefghijklmnopqrstuvwxyz'
    upper = lower.upper()
    num = '01234567890'
    charset = lower + upper + num
    for i in range(0, length): #pylint: disable=unused-variable
        res += random.choice(charset)
    return res

for i in range(50):
    shell_snippet="""(
    DID='{DID}'
    VKEY='~{VKEY}'
    resp=$(curl -sSd "{{\\"network\\":\\"stagingnet\\",\\"did\\":\\"{DID}\\",\\"verkey\\":\\"~{VKEY}\\",\\"paymentaddr\\":\\"\\"}}" http://127.0.0.1:8080/nym 2>&1)
    if [ $? -ne 0 ] ; then
        echo "Request for DID: {DID} and VerKey: ~{VKEY} FAILED!!"
        echo "$resp"
    else
        if echo "$resp" | grep -q '"statusCode": 200' ; then
            echo "Request for DID: {DID} and VerKey: ~{VKEY} was successful"
        else
            echo "Request for DID: {DID} and VerKey: ~{VKEY} FAILED!!"
            echo "$resp"
        fi
    fi
) &""".format(DID=base58.b58encode(rand_str(16)).decode(), VKEY=base58.b58encode(rand_str(16)).decode())
    print(shell_snippet)
print('echo')
print('wait')
Ejemplo n.º 49
0
Archivo: key.py Proyecto: takagotch/btc
import filelock
import json

private_key = ecdsa.SingingKey.generate(curve=ecdsa.SECP256k1)
public_key = private_key.get_verifying_key()

private_key = private_key.to_string()
public_key = public_key.to_string()

print('private key len:', len(private_key))
print('private key hex:', private_key.hex())

print('public key len:', len(public_key))
print('public key hex:', public_key.hex())

private_b58 = base58.b58encode(private_key).decode('ascii')
public_b58 = base58.b58encode(public_key).decode('ascii')

print('private key base58:', private_b58)
print('public key base58:', public_b58)

with filelock.FileLock('key.lock', timeout=10):
    try:
        with open('key.txt', 'r') as file:
            key_list = json.json.load(file)
    except:
        key_list = []

    key_list.append({'private': private_b58, 'public': public_b58})

    with open('key.txt', 'w') as file:
Ejemplo n.º 50
0
def address_checksum(arr):
    hash_val = blake2b_hash(arr)
    str_val = base58.b58encode(hash_val)
    str_val = str_val[:4]
    return str_val
Ejemplo n.º 51
0
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sys

try:
    import base58
except ImportError:
    exit(-1) # base58 is not installed

data = sys.stdin.buffer.read()
data = base58.b58encode(data)
sys.stdout.buffer.write(data)
Ejemplo n.º 52
0
import hashlib
import base58

# answer to https://bitcoin.stackexchange.com/questions/96190
# WIF to private key by https://en.bitcoin.it/wiki/Wallet_import_format
Private_key = base58.b58decode_check(
    "5JYJWrRd7sbqEzL9KR9dYTGrxyLqZEhPtnCtcvhC5t8ZvWgS9iC")
Private_key = Private_key[1:]

# Private key to public key (ecdsa transformation)
signing_key = ecdsa.SigningKey.from_string(Private_key, curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()

# hash sha 256 of pubkey
sha256_1 = hashlib.sha256(public_key)

# hash ripemd of sha of pubkey
ripemd160 = hashlib.new("ripemd160")
ripemd160.update(sha256_1.digest())

# checksum
hashed_public_key = bytes.fromhex("00") + ripemd160.digest()
checksum_full = hashlib.sha256(
    hashlib.sha256(hashed_public_key).digest()).digest()
checksum = checksum_full[:4]
bin_addr = hashed_public_key + checksum

# encode address to base58 and print
result_address = base58.b58encode(bin_addr)
print("Bitcoin address {}".format(result_address))
Ejemplo n.º 53
0
sql_statement = sqlpart1 + sqlpart2

#database = sqlite3.connect('/home/douglasrfix/IntraGalacticMediaService.db', isolation_level=None)
database = sqlite3.connect('/home/douglasrfix/IntraGalacticMediaService.db')
cursor = database.cursor()
ipfs_server = ipfshttpclient.connect(timeout=(20.0, 400))
#uncommitedInserts = 1

#while True:

try:
    with ipfs_server.pubsub.subscribe('IntraGalacticMediaService') as subscription:
        for message in subscription:

            decoded_message_from = base64.standard_b64decode(message['from'])
            base58_encoded_author_peerID = base58.b58encode(decoded_message_from) #BITCOIN_ALPHABET
            decoded_IPNS_name = base64.standard_b64decode(message['data'])
            decoded_seqno = int.from_bytes(base64.standard_b64decode(message['seqno']), byteorder='big', signed=False)
            string_topicIDs_list = str(message['topicIDs'])
            string_message = str(message)
            cursor.execute(sql_statement, [base58_encoded_author_peerID, decoded_IPNS_name, decoded_seqno, string_topicIDs_list, string_message])
            database.commit()

except requests.exceptions.ConnectionError as e:
    print(e)
        #if uncommitedInserts > 0:
            #database.commit()
            #uncommitedInserts = 0

    #except KeyboardInterrupt:
        #database.commit()
Ejemplo n.º 54
0
def get_bitcoin_address(public_key, prefix=b'\x00'):
    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(hashlib.sha256(public_key).digest())
    a = prefix + ripemd160.digest()
    checksum = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    return b58encode(a + checksum)
Ejemplo n.º 55
0
def to_base58(family):
    return base58.b58encode(family.encode('utf-8')).decode('utf-8')
Ejemplo n.º 56
0
 def email_hash(self) -> str:
     """Public identifier string for email address, usable in URLs."""
     return base58.b58encode(self.blake2b160).decode()
Ejemplo n.º 57
0
def hexToBase58(key):
    payload_str = '1C' + key
    payload_unhex = binascii.unhexlify(payload_str)
    checksum = doubleSha256(payload_str)[0:4]
    return base58.b58encode(payload_unhex + checksum, base58.RIPPLE_ALPHABET)
Ejemplo n.º 58
0
 def rawToFriendly(self, raw):
     return base58.b58encode(raw).decode("utf-8")
Ejemplo n.º 59
0
 def hashToStr(h):
     return base58.b58encode(h)
Ejemplo n.º 60
0
def address_to_string(public_key):
    return "H" + base58.b58encode(public_key) + address_checksum(public_key)