我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用base58.b58decode()。
def solve(x): cry = x clear = base58.b58decode(cry) li = list() for i in clear: li.append(ord(i)) ori = clear[:-4] #chk = clear[-4:] rechk = hashlib.sha256(ori).digest() rechk = hashlib.sha256(rechk).digest() #a = list() #for i in rechk: # a.append(ord(i)) checksum = rechk[:4] final = ori+checksum return base58.b58encode(final)
def reissueAsset(self, Asset, quantity, reissuable=False, txFee=pywaves.DEFAULT_TX_FEE): timestamp = int(time.time() * 1000) sData = b'\5' + \ base58.b58decode(self.publicKey) + \ base58.b58decode(Asset.assetId) + \ struct.pack(">Q", quantity) + \ (b'\1' if reissuable else b'\0') + \ struct.pack(">Q",txFee) + \ struct.pack(">Q", timestamp) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "assetId": Asset.assetId, "quantity": quantity, "timestamp": timestamp, "reissuable": reissuable, "fee": txFee, "signature": signature }) req = pywaves.wrapper('/assets/broadcast/reissue', data) if pywaves.OFFLINE: return req else: return req.get('id', 'ERROR')
def burnAsset(self, Asset, quantity, txFee=pywaves.DEFAULT_TX_FEE): timestamp = int(time.time() * 1000) sData = '\6' + \ base58.b58decode(self.publicKey) + \ base58.b58decode(Asset.assetId) + \ struct.pack(">Q", quantity) + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "assetId": Asset.assetId, "quantity": quantity, "timestamp": timestamp, "fee": txFee, "signature": signature }) req = pywaves.wrapper('/assets/broadcast/burn', data) if pywaves.OFFLINE: return req else: return req.get('id', 'ERROR')
def cancelOrder(self, assetPair, order): if not pywaves.OFFLINE: if order.status() == 'Filled': logging.error("Order already filled") elif not order.status(): logging.error("Order not found") sData = base58.b58decode(self.publicKey) + \ base58.b58decode(order.orderId) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "sender": self.publicKey, "orderId": order.orderId, "signature": signature }) req = pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId=='' else assetPair.asset2.assetId), data, host=pywaves.MATCHER) if pywaves.OFFLINE: return req else: id = -1 if req['status'] == 'OrderCanceled': id = req['orderId'] logging.info('Order Cancelled - ID: %s' % id) return id
def cancelOrderByID(self, assetPair, orderId): sData = base58.b58decode(self.publicKey) + \ base58.b58decode(orderId) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "sender": self.publicKey, "orderId": orderId, "signature": signature }) req = pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId=='' else assetPair.asset2.assetId), data, host=pywaves.MATCHER) if pywaves.OFFLINE: return req else: id = -1 if req['status'] == 'OrderCanceled': id = req['orderId'] logging.info('Order Cancelled - ID: %s' % id) return id
def createAlias(self, alias, txFee=pywaves.DEFAULT_ALIAS_FEE, timestamp=0): aliasWithNetwork = b'\x02' + str(pywaves.CHAIN_ID) + struct.pack(">H", len(alias)) + crypto.str2bytes(alias) if not self.privateKey: logging.error('Private key required') else: if timestamp == 0: timestamp = int(time.time() * 1000) sData = b'\x0a' + \ base58.b58decode(self.publicKey) + \ struct.pack(">H", len(aliasWithNetwork)) + \ crypto.str2bytes(aliasWithNetwork) + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "alias": alias, "senderPublicKey": self.publicKey, "fee": txFee, "timestamp": timestamp, "signature": signature }) return pywaves.wrapper('/alias/broadcast/create', data)
def multihash_ref(ref): if isinstance(ref, MultihashReference): return ref try: ref = ref.reference except AttributeError: pass try: ref = ref['@link'] except (TypeError, KeyError): pass try: ref = base58.b58decode(ref) except ValueError: pass return MultihashReference(multihash=ref)
def ToScriptHash(self, address): """ Retrieve the script_hash based from an address. Args: address (str): a base58 encoded address. Raises: ValuesError: if an invalid address is supplied or the coin version is incorrect. Exception: if the address checksum fails. Returns: UInt160: script hash. """ data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != self.AddressVersion: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash256(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21])
def _fulfillment_from_details(data, _depth=0): """Load a fulfillment for a signing spec dictionary Args: data: tx.output[].condition.details dictionary """ if _depth == 100: raise ThresholdTooDeep() if data['type'] == 'ed25519-sha-256': public_key = base58.b58decode(data['public_key']) return Ed25519Sha256(public_key=public_key) if data['type'] == 'threshold-sha-256': threshold = ThresholdSha256(data['threshold']) for cond in data['subconditions']: cond = _fulfillment_from_details(cond, _depth+1) threshold.add_subfulfillment(cond) return threshold raise UnsupportedTypeError(data.get('type'))
def btc_addr_to_hash_160(btc_addr): """ Calculates the RIPEMD-160 hash from a given Bitcoin address :param btc_addr: Bitcoin address. :type btc_addr: str :return: The corresponding RIPEMD-160 hash. :rtype: hex str """ # Base 58 decode the Bitcoin address. decoded_addr = b58decode(btc_addr) # Covert the address from bytes to hex. decoded_addr_hex = hexlify(decoded_addr) # Obtain the RIPEMD-160 hash by removing the first and four last bytes of the decoded address, corresponding to # the network version and the checksum of the address. h160 = decoded_addr_hex[2:-8] return h160
def get(self, address=None): if address is None: raise HTTPError(400, reason="No address") try: from_height = long(self.get_argument("from_height", 0)) except: raise HTTPError(400) address_decoded = base58.b58decode(address) address_version = address_decoded[0] address_hash = address_decoded[1:21] request = { "id": random_id_number(), "command":"fetch_history", "params": [address_version, address_hash, from_height] } self.application._obelisk_handler.handle_request(self, request)
def parse_dict(self, data): """ Generate fulfillment payload from a dict Args: data (dict): description of the fulfillment Returns: Fulfillment """ self.public_key = base58.b58decode(data['public_key']) if data['signature']: self.signature = base58.b58decode(data['signature']) # TODO Adapt according to outcomes of # https://github.com/rfcs/crypto-conditions/issues/16
def sendAsset(pubKey, privKey, recipient, assetId, amount, txfee): timestamp = int(time.time() * 1000) sData = '\4' + base58.b58decode(pubKey) + '\1' + base58.b58decode(assetId) + '\0' + struct.pack(">Q", timestamp) + struct.pack(">Q", amount) + struct.pack(">Q", txfee) + base58.b58decode(recipient) + '\0\0' random64 = os.urandom(64) signature = base58.b58encode(curve.calculateSignature(random64, base58.b58decode(privKey), sData)) data = json.dumps({ "assetId": assetId, "senderPublicKey": pubKey, "recipient": recipient, "amount": amount, "fee": txfee, "timestamp": timestamp, "attachment": "", "signature": signature }) c = pycurl.Curl() c.setopt(pycurl.URL, "http://%s:%s/assets/broadcast/transfer" % (NODE_IP, NODE_PORT)) c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']) c.setopt(pycurl.POST, 1) c.setopt(pycurl.POSTFIELDS, data) c.perform() c.close()
def commit(self, txnCount, stateRoot, txnRoot) -> List: """ :param txnCount: The number of requests to commit (The actual requests are picked up from the uncommitted list from the ledger) :param stateRoot: The state trie root after the txns are committed :param txnRoot: The txn merkle root after the txns are committed :return: list of committed transactions """ (seqNoStart, seqNoEnd), committedTxns = \ self.ledger.commitTxns(txnCount) stateRoot = base58.b58decode(stateRoot.encode()) # Probably the following assertion fail should trigger catchup assert self.ledger.root_hash == txnRoot, '{} {}'.format( self.ledger.root_hash, txnRoot) self.state.commit(rootHash=stateRoot) return txnsWithSeqNo(seqNoStart, seqNoEnd, committedTxns)
def solve(x): base58char = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' for i in range(len(x)): for char in base58char: cry = x[:i]+char+x[i+1:] print cry clear = base58.b58decode(str(cry)) ori = clear[:-4] chk = clear[-4:] rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest() if chk == rechk[:4]: return cry for i in range(len(x)): for j in range(len(x)): if i == j: continue for charI in base58char: for charJ in base58char: cry = x[:i]+charI+x[i+1:] cry = cry[:j]+charJ+cry[j+1:] print cry clear = base58.b58decode(str(cry)) ori = clear[:-4] chk = clear[-4:] rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest() if chk == rechk[:4]: return cry ''' clear = base58.b58decode(str(cry)) #li = list() #for i in clear: # li.append(ord(i)) ori = clear[:-4] chk = clear[-4:] rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest() checksum = rechk[:4] final = ori+checksum return base58.b58encode(final) ''' #print solve(cry) #print solve('15GJF8Do1NDSMy4eV8H82dfFtTvKaqYyhg')
def b58hex(b58): try: return base58.b58decode(b58, None).encode('hex_codec') except Exception: raise PageNotFound()
def shortlink_block(link): try: data = base58.b58decode(link, None) except Exception: raise PageNotFound() return ('00' * ord(data[0])) + data[1:].encode('hex_codec')
def decode_address(addr): bytes = base58.b58decode(addr, None) if len(bytes) < 25: bytes = ('\0' * (25 - len(bytes))) + bytes return bytes[:-24], bytes[-24:-4]
def _generate(self, privateKey='', seed=''): self.seed = seed if not privateKey and not seed: wordCount = 2048 words = [] for i in range(5): r = crypto.bytes2str(os.urandom(4)) x = (ord(r[3])) + (ord(r[2]) << 8) + (ord(r[1]) << 16) + (ord(r[0]) << 24) w1 = x % wordCount w2 = ((int(x / wordCount) >> 0) + w1) % wordCount w3 = ((int((int(x / wordCount) >> 0) / wordCount) >> 0) + w2) % wordCount words.append(wordList[w1]) words.append(wordList[w2]) words.append(wordList[w3]) self.seed = ' '.join(words) seedHash = crypto.hashChain(('\0\0\0\0' + self.seed).encode('utf-8')) accountSeedHash = crypto.sha256(seedHash) if not privateKey: privKey = curve.generatePrivateKey(accountSeedHash) else: privKey = base58.b58decode(privateKey) pubKey = curve.generatePublicKey(privKey) unhashedAddress = chr(1) + str(pywaves.CHAIN_ID) + crypto.hashChain(pubKey)[0:20] addressHash = crypto.hashChain(crypto.str2bytes(unhashedAddress))[0:4] self.address = base58.b58encode(crypto.str2bytes(unhashedAddress + addressHash)) self.publicKey = base58.b58encode(pubKey) self.privateKey = base58.b58encode(privKey)
def issueAsset(self, name, description, quantity, decimals=0, reissuable=False, txFee=pywaves.DEFAULT_ASSET_FEE): if not self.privateKey: logging.error('Private key required') elif len(name) < 4 or len(name) > 16: logging.error('Asset name must be between 4 and 16 characters long') else: timestamp = int(time.time() * 1000) sData = b'\3' + \ base58.b58decode(self.publicKey) + \ struct.pack(">H", len(name)) + \ crypto.str2bytes(name) + \ struct.pack(">H", len(description)) + \ crypto.str2bytes(description) + \ struct.pack(">Q", quantity) + \ struct.pack(">B", decimals) + \ (b'\1' if reissuable else b'\0') + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) signature=crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "name": name, "quantity": quantity, "timestamp": timestamp, "description": description, "decimals": decimals, "reissuable": reissuable, "fee": txFee, "signature": signature }) req = pywaves.wrapper('/assets/broadcast/issue', data) if pywaves.OFFLINE: return req else: return pywaves.Asset(req['assetId'])
def sendWaves(self, recipient, amount, attachment='', txFee=pywaves.DEFAULT_TX_FEE, timestamp=0): if not self.privateKey: logging.error('Private key required') elif amount <= 0: logging.error('Amount must be > 0') elif not pywaves.OFFLINE and self.balance() < amount + txFee: logging.error('Insufficient Waves balance') else: if timestamp == 0: timestamp = int(time.time() * 1000) sData = b'\4' + \ base58.b58decode(self.publicKey) + \ b'\0\0' + \ struct.pack(">Q", timestamp) + \ struct.pack(">Q", amount) + \ struct.pack(">Q", txFee) + \ base58.b58decode(recipient.address) + \ struct.pack(">H", len(attachment)) + \ crypto.str2bytes(attachment) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "recipient": recipient.address, "amount": amount, "fee": txFee, "timestamp": timestamp, "attachment": base58.b58encode(crypto.str2bytes(attachment)), "signature": signature }) return pywaves.wrapper('/assets/broadcast/transfer', data)
def lease(self, recipient, amount, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0): if not self.privateKey: logging.error('Private key required') elif amount <= 0: logging.error('Amount must be > 0') elif not pywaves.OFFLINE and self.balance() < amount + txFee: logging.error('Insufficient Waves balance') else: if timestamp == 0: timestamp = int(time.time() * 1000) sData = b'\x08' + \ base58.b58decode(self.publicKey) + \ base58.b58decode(recipient.address) + \ struct.pack(">Q", amount) + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "recipient": recipient.address, "amount": amount, "fee": txFee, "timestamp": timestamp, "signature": signature }) req = pywaves.wrapper('/leasing/broadcast/lease', data) if pywaves.OFFLINE: return req else: return req['id']
def leaseCancel(self, leaseId, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0): if not self.privateKey: logging.error('Private key required') elif not pywaves.OFFLINE and self.balance() < txFee: logging.error('Insufficient Waves balance') else: if timestamp == 0: timestamp = int(time.time() * 1000) sData = b'\x09' + \ base58.b58decode(self.publicKey) + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) + \ base58.b58decode(leaseId) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "txId": leaseId, "fee": txFee, "timestamp": timestamp, "signature": signature }) req = pywaves.wrapper('/leasing/broadcast/cancel', data) if pywaves.OFFLINE: return req elif 'leaseId' in req: return req['leaseId']
def cancelOpenOrders(self, assetPair): orders = self.getOrderHistory(assetPair) for order in orders: status = order['status'] orderId = order['id'] if status=='Accepted' or status=='PartiallyFilled': sData = base58.b58decode(self.publicKey) + \ base58.b58decode(orderId) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "sender": self.publicKey, "orderId": orderId, "signature": signature }) pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId == '' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId == '' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
def deleteOrderHistory(self, assetPair): orders = self.getOrderHistory(assetPair) for order in orders: orderId = order['id'] sData = base58.b58decode(self.publicKey) + \ base58.b58decode(orderId) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "sender": self.publicKey, "orderId": orderId, "signature": signature }) pywaves.wrapper('/matcher/orderbook/%s/%s/delete' % ('WAVES' if assetPair.asset1.assetId == '' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId == '' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
def sign(privateKey, message): random64 = os.urandom(64) return base58.b58encode(curve.calculateSignature(random64, base58.b58decode(privateKey), message))
def simpleDecrypt(self, passphrase, base58_data): """Decrypt data. Args: passphrase (str): passphrase to use for decryption. base58_data (str/bytes): base58-encoded encrypted data. Returns: (str): original data. """ key, iv = self.EVP_BytesToKey(passphrase, 32, 16) return self.decrypt(base58.b58decode(base58_data), key, iv)
def ascii2bytes(s): """ >>> ascii2bytes('3yZe7d') b'test' """ return b58decode(s)
def ascii2pet(s): """ >>> ascii2pet('3Xw3vNAdCmDLs') EcPt(00) """ return decode(b58decode(s))
def from_base58(cls, base58str): byte_string = b58decode(base58str) return cls(byte_string)
def verifySignature(self, msg: Dict[str, str]): signature = msg.get(f.SIG.nm) identifier = msg.get(IDENTIFIER) msgWithoutSig = {k: v for k, v in msg.items() if k != f.SIG.nm} # TODO This assumes the current key is the cryptonym. This is a BAD # ASSUMPTION!!! Sovrin needs to provide the current key. ser = serializeMsg(msgWithoutSig) signature = b58decode(signature.encode()) typ = msg.get(TYPE) # TODO: Maybe keeping ACCEPT_INVITE open is a better option than keeping # an if condition here? if typ == ACCEPT_INVITE: verkey = msg.get(VERKEY) else: try: link = self.getLinkForMsg(msg) verkey = self.getVerkeyForLink(link) except (LinkNotFound, VerkeyNotFound): # This is for verification of `NOTIFY` events link = self.wallet.getLinkBy(remote=identifier) # TODO: If verkey is None, it should be fetched from Sovrin. # Assuming CID for now. verkey = link.remoteVerkey v = DidVerifier(verkey, identifier=identifier) if not v.verify(signature, ser): raise SignatureRejected else: if typ == ACCEPT_INVITE: self.logger.info('Signature accepted.') return True
def _getNym(self, nym): identity = Identity(identifier=nym) req = self.activeWallet.requestIdentity( identity, sender=self.activeWallet.defaultId) self.activeClient.submitReqs(req) self.print("Getting nym {}".format(nym)) def getNymReply(reply, err, *args): try: if err: self.print("Error: {}".format(err), Token.BoldOrange) return if reply and reply[DATA]: data=json.loads(reply[DATA]) if data: idr = base58.b58decode(nym) if data.get(VERKEY) is None: if len(idr) == 32: self.print( "Current verkey is same as identifier {}" .format(nym), Token.BoldBlue) else: self.print( "No verkey ever assigned to the identifier {}". format(nym), Token.BoldBlue) return if data.get(VERKEY) == '': self.print("No active verkey found for the identifier {}". format(nym), Token.BoldBlue) else: self.print("Current verkey for NYM {} is {}". format(nym, data[VERKEY]), Token.BoldBlue) else: self.print("NYM {} not found".format(nym), Token.BoldBlue) except BaseException as e: self.print("Error during fetching verkey: {}".format(e), Token.BoldOrange) self.looper.loop.call_later(.2, self._ensureReqCompleted, req.key, self.activeClient, getNymReply)
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), DATA: b58encode(boxedMsg) } self.submit(op, identifier=origin)
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif))) data = base58.b58decode(wif) length = len(data) if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01: raise ValueError("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise ValueError("Invalid WIF Checksum!") return data[1:33]
def AddrStrToScriptHash(address): data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != settings.ADDRESS_VERSION: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash256(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21])
def verifySignature(self, msg: Dict[str, str]): signature = msg.get(f.SIG.nm) identifier = msg.get(IDENTIFIER) msgWithoutSig = {k: v for k, v in msg.items() if k != f.SIG.nm} # TODO This assumes the current key is the cryptonym. This is a BAD # ASSUMPTION!!! Indy needs to provide the current key. ser = serialize_msg_for_signing(msgWithoutSig) signature = b58decode(signature.encode()) typ = msg.get(TYPE) # TODO: Maybe keeping ACCEPT_INVITE open is a better option than keeping # an if condition here? if typ == ACCEPT_INVITE: verkey = msg.get(VERKEY) else: try: link = self.getLinkForMsg(msg) verkey = self.getVerkeyForLink(link) except (ConnectionNotFound, VerkeyNotFound): # This is for verification of `NOTIFY` events link = self.wallet.getConnectionBy(remote=identifier) # TODO: If verkey is None, it should be fetched from Indy. # Assuming CID for now. verkey = link.remoteVerkey v = DidVerifier(verkey, identifier=identifier) if not v.verify(signature, ser): raise SignatureRejected else: if typ == ACCEPT_INVITE: self.logger.info('Signature accepted.') return True
def verifySig(identifier, signature, msg) -> bool: key = cryptonymToHex(identifier) if not isHex( identifier) else identifier ser = serialize_msg_for_signing(msg) b64sig = signature.encode('utf-8') sig = b58decode(b64sig) vr = Verifier(key) return vr.verify(sig, ser)
def commit(self, txnCount, stateRoot, txnRoot) -> List: r = super().commit(txnCount, stateRoot, txnRoot) stateRoot = base58.b58decode(stateRoot.encode()) self.idrCache.onBatchCommitted(stateRoot) return r
def verifyMsg(verifier, sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning)
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs): """Signs a Ed25519Fulfillment. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The input to be signed. message (str): The message to be signed key_pairs (dict): The keys to sign the Transaction with. """ # NOTE: To eliminate the dangers of accidentally signing a condition by # reference, we remove the reference of input_ here # intentionally. If the user of this class knows how to use it, # this should never happen, but then again, never say never. input_ = deepcopy(input_) public_key = input_.owners_before[0] try: # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings input_.fulfillment.sign( message.encode(), base58.b58decode(key_pairs[public_key].encode()), ) except KeyError: raise KeypairMismatchException('Public key {} is not a pair to ' 'any of the private keys' .format(public_key)) return input_
def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs): """Signs a ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. message (str): The message to be signed key_pairs (dict): The keys to sign the Transaction with. """ input_ = deepcopy(input_) for owner_before in set(input_.owners_before): # TODO: CC should throw a KeypairMismatchException, instead of # our manual mapping here # TODO FOR CC: Naming wise this is not so smart, # `get_subcondition` in fact doesn't return a # condition but a fulfillment # TODO FOR CC: `get_subcondition` is singular. One would not # expect to get a list back. ccffill = input_.fulfillment subffills = ccffill.get_subcondition_from_vk( base58.b58decode(owner_before)) if not subffills: raise KeypairMismatchException('Public key {} cannot be found ' 'in the fulfillment' .format(owner_before)) try: private_key = key_pairs[owner_before] except KeyError: raise KeypairMismatchException('Public key {} is not a pair ' 'to any of the private keys' .format(owner_before)) # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings for subffill in subffills: subffill.sign(message.encode(), base58.b58decode(private_key.encode())) return input_
def test_fulfill(self, driver, alice_keypair, unsigned_transaction): signed_transaction = driver.transactions.fulfill( unsigned_transaction, private_keys=alice_keypair.sk) unsigned_transaction['inputs'][0]['fulfillment'] = None message = json.dumps( unsigned_transaction, sort_keys=True, separators=(',', ':'), ensure_ascii=False, ).encode() ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice_keypair.vk)) ed25519.sign(message, base58.b58decode(alice_keypair.sk)) fulfillment_uri = ed25519.serialize_uri() assert signed_transaction['inputs'][0]['fulfillment'] == fulfillment_uri # noqa
def make_ed25519_condition(public_key, *, amount=1): ed25519 = Ed25519Sha256(public_key=base58.b58decode(public_key)) return { 'amount': str(amount), 'condition': { 'details': _fulfillment_to_details(ed25519), 'uri': ed25519.condition_uri, }, 'public_keys': (public_key,), }
def sign_transaction(transaction, *, public_key, private_key): ed25519 = Ed25519Sha256(public_key=base58.b58decode(public_key)) message = json.dumps( transaction, sort_keys=True, separators=(',', ':'), ensure_ascii=False, ) ed25519.sign(message.encode(), base58.b58decode(private_key)) return ed25519.serialize_uri()
def verifySig(identifier, signature, msg) -> bool: key = cryptonymToHex(identifier) if not isHex( identifier) else identifier ser = serializeMsg(msg) b64sig = signature.encode('utf-8') sig = b58decode(b64sig) vr = Verifier(key) return vr.verify(sig, ser)
def WIFkey_to_binPrivateKey(wif): if len(wif) != 52: print 'Error' return None bpk = b58decode(wif)[1:33] return bpk
def address_to_scriptHash(address): return hexlify(b58decode(address)[1:-4])