def liability_read(self, address): ''' Read liability from blockchain to message. ''' c = self.web3.eth.contract(address, abi=self.liability_abi) msg = Liability() model_mh = Multihash() model_mh.multihash = multihash.decode( c.call().model()).encode('base58').decode() objective_mh = Multihash() objective_mh.multihash = multihash.decode( c.call().objective()).encode('base58').decode() msg.address = address msg.model = model_mh msg.objective = objective_mh msg.promisee = c.call().promisee() msg.promisor = c.call().promisor() msg.lighthouse = c.call().lighthouse() msg.token = c.call().token() msg.cost = c.call().cost() msg.validator = c.call().validator() msg.validatorFee = c.call().validatorFee() rospy.logdebug('New liability readed: %s', msg) return msg
def _process_Market_MarketCreated(transactionHash, blockHash, args): # /// Event emitted when a new market was created. # event MarketCreated (bytes16 indexed marketId, uint32 marketSeq, address owner, string terms, string meta, # address maker, uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee); self.log.info( '{event}: processing event (tx_hash={tx_hash}, block_hash={block_hash}) - XBR market created with ID {market_id})', event=hlcontract('XBRMarket.MarketCreated'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode()), block_hash=hlid('0x' + binascii.b2a_hex(blockHash).decode()), market_id=hlid(uuid.UUID(bytes=args.marketId))) market_id = uuid.UUID(bytes=args.marketId) if args.terms: h = multihash.decode(multihash.from_b58_string(args.terms)) if h.name != 'sha2-256': self.log.warn( 'WARNING: XBRMarket.MarketCreated - terms "{terms}" is not an IPFS (sha2-256) b58-encoded multihash', terms=hlval(args.terms)) if args.meta: h = multihash.decode(multihash.from_b58_string(args.meta)) if h.name != 'sha2-256': self.log.warn( 'WARNING: XBRMarket.MarketCreated - meta "{meta}" is not an IPFS (sha2-256) b58-encoded multihash', meta=hlval(args.meta)) stored = False with self._db.begin(write=True) as txn: market = self._xbr.markets[txn, market_id] if market: self.log.warn('{contract}(tx_hash={tx_hash}) record already stored in database.', contract=hlcontract('MarketCreated'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode())) else: market = cfxdb.xbr.market.Market() market.market = market_id market.timestamp = np.datetime64(time_ns(), 'ns') # FIXME # market.created = args.created market.seq = args.marketSeq market.owner = bytes(HexBytes(args.owner)) market.terms = args.terms market.meta = args.meta market.maker = bytes(HexBytes(args.maker)) market.provider_security = args.providerSecurity market.consumer_security = args.consumerSecurity market.market_fee = args.marketFee self._xbr.markets[txn, market_id] = market stored = True if stored: self.log.info('new {contract}(market_id={market_id}) record stored database!', contract=hlcontract('MarketCreated'), market_id=hlid(market_id))
def from_bytes(cidbytes): """ Creates a CID object from a encoded form :param bytes cidbytes: can be - base58-encoded multihash - multihash - multibase-encoded multihash :return: a CID object :rtype: :py:class:`cid.CIDv0` or :py:class:`cid.CIDv1` :raises: `ValueError` if the base58-encoded string is not a valid string :raises: `ValueError` if the length of the argument is zero :raises: `ValueError` if the length of decoded CID is invalid """ if len(cidbytes) < 2: raise ValueError('argument length can not be zero') # first byte for identity multibase and CIDv0 is 0x00 # putting in assumption that multibase for CIDv0 can not be identity # refer: https://github.com/ipld/cid/issues/13#issuecomment-326490275 if cidbytes[0] != 0 and multibase.is_encoded(cidbytes): # if the bytestream is multibase encoded cid = multibase.decode(cidbytes) if len(cid) < 2: raise ValueError('cid length is invalid') data = cid[1:] version = int(cid[0]) codec = multicodec.get_codec(data) multihash = multicodec.remove_prefix(data) elif cidbytes[0] in (0, 1): # if the bytestream is a CID version = cidbytes[0] data = cidbytes[1:] codec = multicodec.get_codec(data) multihash = multicodec.remove_prefix(data) else: # otherwise its just base58-encoded multihash try: version = 0 codec = CIDv0.CODEC multihash = base58.b58decode(cidbytes) except ValueError: raise ValueError( 'multihash is not a valid base58 encoded multihash') try: mh.decode(multihash) except ValueError: raise return make_cid(version, codec, multihash)
def encodeBid(msg): args = [ multihash.decode(msg.model.multihash.encode(), 'base58').encode(), multihash.decode(msg.objective.multihash.encode(), 'base58').encode(), msg.token, msg.cost, msg.validator, msg.lighthouse, msg.lighthouseFee, msg.deadline, msg.nonce, msg.signature ] return '0x' + liability.functions.offer( *args).buildTransaction()['data'][10:]
def isMultihash(hashstring): """ Check if hashstring is a valid base58-encoded multihash :param str hashstring: the multihash to validate :return: if the value is a valid multihash or not :rtype: bool """ try: multihash.decode(hashstring.encode('ascii'), 'base58') return True except BaseException: return False
def offer_hash(msg, nonce): types = [ 'bytes', 'bytes', 'address', 'uint256', 'address', 'address', 'uint256', 'uint256', 'uint256', 'address' ] return Web3.soliditySha3(types, [ multihash.decode(msg.model.multihash.encode(), 'base58').encode(), multihash.decode(msg.objective.multihash.encode(), 'base58').encode(), msg.token.address, int(msg.cost.uint256), msg.validator.address, msg.lighthouse.address, int(msg.lighthouseFee.uint256), int(msg.deadline.uint256), int(nonce.uint256), msg.sender.address ])
def _process_Network_MemberRegistered(transactionHash, blockHash, args): # /// Event emitted when a new member joined the XBR Network. # event MemberCreated (address indexed member, string eula, string profile, MemberLevel level); self.log.info( '{event}: processing event (tx_hash={tx_hash}, block_hash={block_hash}) - XBR member created at address {address})', event=hlcontract('XBRNetwork.MemberCreated'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode()), block_hash=hlid('0x' + binascii.b2a_hex(blockHash).decode()), address=hlid(args.member)) member_adr = bytes(HexBytes(args.member)) if args.eula: h = multihash.decode(multihash.from_b58_string(args.eula)) if h.name != 'sha2-256': self.log.warn( 'WARNING: XBRNetwork.MemberCreated - eula "{eula}" is not an IPFS (sha2-256) b58-encoded multihash', eula=hlval(args.eula)) if args.profile: h = multihash.decode(multihash.from_b58_string(args.profile)) if h.name != 'sha2-256': self.log.warn( 'WARNING: XBRNetwork.MemberCreated - profile "{profile}" is not an IPFS (sha2-256) b58-encoded multihash', eula=hlval(args.profile)) stored = False with self._db.begin(write=True) as txn: member = self._xbr.members[txn, member_adr] if member: self.log.warn('{contract}(tx_hash={tx_hash}) record already stored in database.', contract=hlcontract('TokenApproval'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode())) else: member = cfxdb.xbr.member.Member() member.address = member_adr member.timestamp = np.datetime64(time_ns(), 'ns') member.registered = args.registered member.eula = args.eula member.profile = args.profile member.level = args.level self._xbr.members[txn, member_adr] = member stored = True if stored: self.log.info('new {contract}(member_adr={member_adr}) record stored database!', contract=hlcontract('MemberCreated'), member_adr=hlid('0x' + binascii.b2a_hex(member_adr).decode()))
def cidInfosMarkup(cidString): try: cid = getCID(cidString) mhash = multihash.decode(cid.multihash) baseEncoding = multibase.multibase.get_codec(cidString) except: return '<p>Invalid CID</p>' return ''' <p>CID: <b>{cids}</b></p> <p>CID version {cidv}</p> <p>Multibase encoding: <b>{mbase}</b></p> <p>Codec: <b>{codec}</b></p> <p>Multihash function: <b>{mhashfunc}</b></p> <p>Multihash function code: {mhashfuncvalue} (<b>{mhashfuncvaluehex}</b>)</p> <p>Multihash digest: <b>{mhashdigest}</b></p> <p>Multihash: <b>{mhashascii}</b></p> '''.format(cids=cidString, cidv=cid.version, mbase=baseEncoding.encoding if baseEncoding else iUnknown(), codec=cid.codec, mhashfunc=mhash.name, mhashfuncvalue=mhash.code, mhashfuncvaluehex=hex(mhash.code), mhashdigest=binascii.b2a_hex(mhash.digest).decode('ascii'), mhashascii=binascii.b2a_hex(cid.multihash).decode('ascii'))
def test_cids(self): assert cidValid( 'bafkriqa2hf4uwu2dd2nlynbwr3kietn2ywowyzaxperhtmhmfsi5n22yv5zptvfr4o3bhicyshbmdil2qif47au4wmr4ikm3egpfvmuzpfcyc' ) assert cidValid( 'bafkreihszin3nr7ja7ig3l7enb7fph6oo2zx4tutw5qfaiw2kltmzqtp2i') assert cidValid( 'bafkrgqaohz2sgsv4nd2dpcugwp2lgkqzrorqdbc3btlokaig5b2divyazrtghkdmd2qslxc6sk7bpsmptihylsu5l5mv3mqbf56mgvyzixasg' ) assert cidValid( 'bafkr2qffyprvhimferhyfkg6af63marfiplxn6euhncxwy3izaefj3g73ilqlzo5kfgvbbyrnwwmw7nm4wwufkyxfp7htiwabn5b5hdw4rvvk' ) p = IPFSPath( 'bafkr2qffyprvhimferhyfkg6af63marfiplxn6euhncxwy3izaefj3g73ilqlzo5kfgvbbyrnwwmw7nm4wwufkyxfp7htiwabn5b5hdw4rvvk' ) assert p.valid p = IPFSPath( 'bafk4bzacia2aon3c3n5pkaemoij7sm4q4dt3omcr5tkc2sptmm6ifsnpbsx7h77xj4e4pjx7olxtbgsyjsg35mgl3j2q7mel3kuiz2v7ztngkdbv' ) assert p.valid p = IPFSPath( '/ipfs/bafykbzaced4xstofs4tc5q4irede6uzaz3qzcdvcb2eedxgfakzwdyjnxgohq/' ) assert p.valid cid = getCID( 'bafykbzaced4xstofs4tc5q4irede6uzaz3qzcdvcb2eedxgfakzwdyjnxgohq') m = multihash.decode(cid.multihash) assert m.name == 'blake2b-256'
def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True): """ Get file from ipfs We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise """ if validate: from snet_cli.resources.proto.unixfs_pb2 import Data from snet_cli.resources.proto.merckledag_pb2 import MerkleNode # No nice Python library to parse ipfs blocks, so do it ourselves. block_data = ipfs_client.block_get(ipfs_hash_base58) mn = MerkleNode() mn.ParseFromString(block_data) unixfs_data = Data() unixfs_data.ParseFromString(mn.Data) assert unixfs_data.Type == unixfs_data.DataType.Value('File'), "IPFS hash must be a file" data = unixfs_data.Data # multihash has a badly registered base58 codec, overwrite it... multihash.CodecReg.register('base58', base58.b58encode, base58.b58decode) # create a multihash object from our ipfs hash mh = multihash.decode(ipfs_hash_base58.encode('ascii'), 'base58') # Convenience method lets us directly use a multihash to verify data if not mh.verify(block_data): raise Exception("IPFS hash mismatch with data") else: data = ipfs_client.cat(ipfs_hash_base58) return data
def verify(mh: bytes, buffer: bytes) -> bool: if not isinstance(buffer, bytes): raise TypeError('buffer must be a bytes object, not {}'.format( type(buffer))) decoded = multihash.decode(mh) encoded = multihashing(buffer, decoded.name, decoded.length) return encoded == mh
def test_decode_sha1(): mh_bytes = six.b('\x11(86f7e437faa5a7fce15d1ddcb9eaeaea377667b8') mh = multihash.decode(mh_bytes) assert mh.name == 'sha1' assert mh.length == 40 assert mh.code == 0x11 assert mh.digest == '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8'
def result_hash(msg): types = ['address', 'bytes', 'bool'] return Web3.soliditySha3(types, [ msg.liability.address, multihash.decode(msg.result.multihash.encode(), 'base58').encode(), msg.success ])
def _validate_asset_file_checksum(href, expected_multihash, asset_multihash): expected_multihash = multihash.decode(from_hex_string(expected_multihash)) logger.debug( 'Validate asset file checksum at %s with multihash %s/%s (from headers), expected %s/%s ' '(from checksum:multishash attribute)', href, to_hex_string(asset_multihash.digest), asset_multihash.name, to_hex_string(expected_multihash.digest), expected_multihash.name) if asset_multihash.name != expected_multihash.name: logger.error( 'Asset at href %s, with multihash name=%s digest=%s, doesn\'t match the expected ' 'multihash name=%s digest=%s defined in checksum:multihash attribute', href, asset_multihash.name, to_hex_string(asset_multihash.digest), expected_multihash.name, to_hex_string(expected_multihash.digest)) raise serializers.ValidationError({ 'href': _(f"Asset at href {href} has a {asset_multihash.name} multihash while a " f"{expected_multihash.name} multihash is defined in the checksum:multihash " "attribute") }) if asset_multihash != expected_multihash: logger.error( 'Asset at href %s, with multihash name=%s digest=%s, doesn\'t match the ' 'checksum:multihash value name=%s digest=%s', href, asset_multihash.name, to_hex_string(asset_multihash.digest), expected_multihash.name, to_hex_string(expected_multihash.digest)) raise serializers.ValidationError({ 'href': _(f"Asset at href {href} with {asset_multihash.name} hash " f"{to_hex_string(asset_multihash.digest)} doesn't match the " f"checksum:multihash {to_hex_string(expected_multihash.digest)}") })
def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True): """ Get file from ipfs We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise """ if validate: from snet_cli.resources.proto.unixfs_pb2 import Data from snet_cli.resources.proto.merckledag_pb2 import MerkleNode # No nice Python library to parse ipfs blocks, so do it ourselves. block_data = ipfs_client.block_get(ipfs_hash_base58) mn = MerkleNode() mn.ParseFromString(block_data) unixfs_data = Data() unixfs_data.ParseFromString(mn.Data) assert unixfs_data.Type == unixfs_data.DataType.Value( 'File'), "IPFS hash must be a file" data = unixfs_data.Data # multihash has a badly registered base58 codec, overwrite it... multihash.CodecReg.register('base58', base58.b58encode, base58.b58decode) # create a multihash object from our ipfs hash mh = multihash.decode(ipfs_hash_base58.encode('ascii'), 'base58') # Convenience method lets us directly use a multihash to verify data if not mh.verify(block_data): raise Exception("IPFS hash mismatch with data") else: data = ipfs_client.cat(ipfs_hash_base58) return data
def cidValid(cid): """ Check if the passed argument is a valid IPFS CID :param cid: the CID to validate, can be a string or a BaseCID :return: if the value is a valid CID or not :rtype: bool """ if cid is None: return False if isinstance(cid, str): c = getCID(cid) elif issubclass(cid.__class__, BaseCID): c = cid else: return False if c is None: return False if c.version in [0, 1]: # Ensure that we can decode the multihash try: # can raise ValueError if multihash.decode(c.multihash): return True except BaseException: return False return False
def demand_hash(msg): types = ['bytes', 'bytes', 'address', 'uint256', 'address', 'address', 'uint256', 'uint256', 'bytes32'] return Web3.soliditySha3(types, [multihash.decode(msg.model.multihash.encode(), "base58").encode(), multihash.decode(msg.objective.multihash.encode(), "base58").encode(), msg.token.address, int(msg.cost.uint256), msg.lighthouse.address, msg.validator.address, int(msg.validatorFee.uint256), int(msg.deadline.uint256), msg.nonce])
def offer_hash(msg): types = ['bytes', 'bytes', 'address', 'uint256', 'address', 'address', 'uint256', 'uint256', 'bytes32'] return Web3.soliditySha3(types, [multihash.decode(msg.model.multihash.encode(), 'base58').encode(), multihash.decode(msg.objective.multihash.encode(), 'base58').encode(), msg.token, msg.cost, msg.validator, msg.lighthouse, msg.lighthouseFee, msg.deadline, msg.nonce])
def from_bytes(cidbytes): """ Creates a CID object from a encoded form :param bytes cidbytes: can be - base58-encoded multihash - multihash - multibase-encoded multihash :return: a CID object :rtype: :py:class:`cid.CIDv0` or :py:class:`cid.CIDv1` :raises: `ValueError` if the base58-encoded string is not a valid string """ if multibase.is_encoded(cidbytes): # if the bytestream is multibase encoded cid = multibase.decode(cidbytes) data = cid[1:] version = int(cid[0]) codec = multicodec.get_codec(data) multihash = multicodec.remove_prefix(data) elif cidbytes[0] in (b'0', b'1'): # if the bytestream is a CID version = cidbytes[0] data = cidbytes[1:] codec = multicodec.get_codec(data) multihash = multicodec.remove_prefix(data) else: # otherwise its just base58-encoded multihash try: version = 0 codec = CIDv0.CODEC multihash = base58.b58decode(cidbytes) except ValueError: raise ValueError( 'multihash is not a valid base58 encoded multihash') try: mh.decode(multihash) except ValueError: raise return make_cid(version, codec, multihash)
def __init__( self, host: str, port: int, public_key: Optional[str] = None, multihash_id: Optional[str] = None, ): """ Initialize a multiaddress. :param host: ip host of the address :param port: port number of the address :param public_key: hex encoded public key. Must conform to Bitcoin EC encoding standard for Secp256k1 :param multihash_id: a multihash of the public key """ self._host = host self._port = port if public_key is not None: try: VerifyingKey._from_compressed(_hex_to_bytes(public_key), curves.SECP256k1) except keys.MalformedPointError as e: # pragma: no cover raise ValueError("Malformed public key '{}': {}".format( public_key, str(e))) self._public_key = public_key self._peerid = self.compute_peerid(self._public_key) elif multihash_id is not None: try: multihash.decode(base58.b58decode(multihash_id)) except Exception as e: raise ValueError("Malformed multihash '{}': {}".format( multihash_id, str(e))) self._public_key = "" self._peerid = multihash_id else: raise ValueError( # pragma: no cover "MultiAddr requires either public_key or multihash_id to be provided." )
def create_multihash(digest, hash_type): '''Returns a multihash from a digest Args: digest: string hash_type: string hash type sha2-256 Returns: multihash multihash ''' return multihash.decode(multihash.encode(multihash.from_hex_string(digest), hash_type))
def get_resolver_data(query, net='ropsten'): registry = web3_data['ENSRegistry']['contract'][net] resol = registry.functions.resolver(ENS.namehash(query)).call() owner = registry.functions.owner(ENS.namehash(query)).call() resolver = w3[net].eth.contract(resol, abi=web3_data['PublicResolver']['abi']) if resolver.functions.supportsInterface( '0x3b3b57de').call(): #addr interface address = resolver.functions.addr(ENS.namehash(query)).call() else: address = '' contenthash = '' onion = '' ipfs = '' swarm = '' if resolver.functions.supportsInterface( '0xbc1c58d1').call(): #contentHash interface contenthashbytes = resolver.functions.contenthash( ENS.namehash(query)).call() print(is_empty_hex(contenthashbytes), 'contenthash') if not is_empty_hex(contenthashbytes): #check codec of multihash mh = multihash.decode(contenthashbytes) print(mh) contenthash = mh.digest.decode('utf-8') if mh.name == 'ipfs-ns': ipfs = contenthash elif mh.name == 'swarm-ns': swarm = contenthash elif (mh.name == 'onion' or mh.name == 'onion3'): onion = contenthash content = '' if resolver.functions.supportsInterface( '0xd8389dc5').call(): #content interface contentbytes = resolver.functions.content(ENS.namehash(query)).call() print(is_empty_hex(contentbytes), 'content') if not is_empty_hex(contentbytes): buffer = multihash.encode(contentbytes, 'sha2-256') content = multihash.to_b58_string(buffer) return { 'owner': owner, 'resolver': resol, 'address': address, 'content': content, 'contenthash': contenthash, 'onion': onion, 'ipfs': ipfs, 'swarm': swarm }
def decode(value): """ Decode HEX multi hash. :param bytes value: an encoded content :return: the decoded content :rtype: str """ cid = make_cid(value) return multihash.to_hex_string(multihash.decode(cid.multihash).digest)
def settle_result(self, msg): ''' Settle incoming result. ''' liability = self.web3.eth.contract(msg.liability, abi=self.liability_abi) data = liability.functions.finalize( multihash.decode(msg.result.multihash.encode(), "base58").encode(), msg.success, msg.signature, False).buildTransaction({'gas': 1000000})['data'] tx = self.lighthouse.functions.to(msg.liability, data)\ .buildTransaction({'gas': 1000000, 'from': self.account_address}) self.manager.put(tx)
def test_decode_app_code(self): """ decode: works for all app codes """ code = 0x08 hex_ = 'fdfdfdfdfd' buffer = make_hash(code, 5, hex_) actual = bytes.fromhex(hex_) r = decode(buffer) expected = r.digest assert r.code == code assert r.length == len(actual) assert actual == expected
def _process_Market_ActorJoined(transactionHash, blockHash, args): # Event emitted when a new actor joined a market. # event ActorJoined (bytes16 indexed marketId, address actor, uint8 actorType, uint joined, uint256 security, string meta); self.log.info( '{event}: processing event (tx_hash={tx_hash}, block_hash={block_hash}) - XBR market actor {actor} joined market {market_id})', event=hlcontract('XBRMarket.ActorJoined'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode()), block_hash=hlid('0x' + binascii.b2a_hex(blockHash).decode()), actor=hlid(args.actor), market_id=hlid(uuid.UUID(bytes=args.marketId))) market_id = uuid.UUID(bytes=args.marketId) actor_adr = bytes(HexBytes(args.actor)) actor_type = int(args.actorType) if args.meta: h = multihash.decode(multihash.from_b58_string(args.meta)) if h.name != 'sha2-256': self.log.warn( 'WARNING: XBRMarket.MarketCreated - meta "{meta}" is not an IPFS (sha2-256) b58-encoded multihash', terms=hlval(args.meta)) stored = False with self._db.begin(write=True) as txn: actor = self._xbr.actors[txn, (market_id, actor_adr, actor_type)] if actor: self.log.warn('{contract}(tx_hash={tx_hash}) record already stored in database.', contract=hlcontract('MarketCreated'), tx_hash=hlid('0x' + binascii.b2a_hex(transactionHash).decode())) else: actor = cfxdb.xbr.actor.Actor() actor.timestamp = np.datetime64(time_ns(), 'ns') actor.market = market_id actor.actor = actor_adr actor.actor_type = actor_type actor.joined = args.joined actor.security = args.security actor.meta = args.meta self._xbr.actors[txn, (market_id, actor_adr, actor_type)] = actor stored = True if stored: self.log.info( 'new {contract}(market_id={market_id}, actor_adr={actor_adr}, actor_type={actor_type}) record stored database!', contract=hlcontract('ActorJoined'), market_id=hlid(market_id), actor_adr=hlid('0x' + binascii.b2a_hex(actor_adr).decode()), actor_type=hlid(actor_type))
def test_decode_valid(self, value): """ decode: works for all valid cases """ code = value['encoding']['code'] buffer = make_hash(code, value['length'], value['hex']) name = value['encoding']['name'] actual = bytes.fromhex(value['hex']) r = decode(buffer) expected = r.digest assert r.code == code assert r.name == name assert r.length == len(actual) assert actual == expected
def test_valid_decode(self, valid): for case in valid: code = case['encoding']['code'] buf = sample(code, case['size'], case['hex']) name = case['encoding']['name'] d1 = bytes.fromhex(case['hex']) r = multihash.decode(buf) d2 = r['digest'] assert r['code'] == code assert r['name'] == name assert r['length'] == len(d1) assert d1 == d2
def parse_multihash(multihash_string): '''Parse a multihash string Args: multihash_string: string multihash string to parse Returns. Multihash object Raises: TypeError: if incoming data is not a string ValueError: if the incoming data is not a valid multihash ''' return multihash.decode(multihash.from_hex_string(multihash_string))
def validate_asset_multihash(value): '''Validate the Asset multihash field The field value must be a multihash string Args: value: string multihash value Raises: ValidationError in case of invalid multihash value ''' try: mhash = multihash.decode(multihash.from_hex_string(value)) except ValueError as error: logger.error("Invalid multihash %s; %s", value, error) raise ValidationError(code='checksum:multihash', message=_('Invalid multihash value; %(error)s'), params={'error': error})
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("cid") args = parser.parse_args() try: c = make_cid(args.cid) except ValueError as e: print(e, file=sys.stderr) sys.exit(1) if c.version == 0: mb_codec = 'base58btc' else: mb_codec = multibase.get_codec(args.cid).encoding mh = multihash.decode(c.multihash) print( f'{mb_codec} - cidv{c.version} - {c.codec} - {mh.name}-{len(mh.digest)*8}-{mh.digest.hex()}' )
def validate_checksum_multihash_sha256(value): '''Validate the checksum multihash field The field value must be a multihash sha256 string Args: value: string multihash value Raises: ValidationError in case of invalid multihash value ''' try: mhash = multihash.decode(multihash.from_hex_string(value)) except (ValueError, TypeError) as error: logger.error("Invalid multihash %s; %s", value, error) raise ValidationError(_('Invalid multihash value; %(error)s'), params={'error': error}, code='invalid') from None if mhash.code != HASH_CODES['sha2-256']: logger.error("Invalid multihash value: must be sha2-256 but is %s", CODE_HASHES[mhash.code]) raise ValidationError(_('Invalid multihash value: must be sha2-256 but is %(code)s'), params={'code': CODE_HASHES[mhash.code]}, code='invalid')
def test_encode_sha1_utf8(): digest = '💻' mh = multihash.MultiHash('sha1', digest) encoded = mh.encode() assert encoded == six.b('\x11\x04\xf0\x9f\x92\xbb') assert multihash.decode(encoded).digest == digest
def test_decode_raises(mh_bytes, exception): with pytest.raises(exception): multihash.decode(mh_bytes)