lib/multihashes.rb in multihashes-0.1.3 vs lib/multihashes.rb in multihashes-0.2.0

- old
+ new

@@ -1,30 +1,25 @@ require 'multihashes/version' +require 'multicodecs' module Multihashes class HashFunctionNotImplemented < StandardError; end class DigestLengthError < StandardError; end - # https://github.com/jbenet/multihash - TABLE = { - 0xd5 => 'md5', - 0x11 => 'sha1', - 0x12 => 'sha2-256', - 0x13 => 'sha2-512', - 0x14 => 'sha3', - 0x40 => 'blake2b', - 0x41 => 'blake2s' - } + # https://github.com/multiformats/multicodec/blob/master/table.csv + TABLE = Multicodecs.where(tag: 'multihash') + .map { |codec| [codec.code, codec.name] } + .to_h def self.encode(digest, hash_function) length = digest.bytesize key = TABLE.key hash_function raise HashFunctionNotImplemented, 'unknown hash function code' if key.nil? - [TABLE.key(hash_function), length, digest].pack("CCA#{length}") + [TABLE.key(hash_function), length, digest].pack("CCa#{length}") end def self.decode(multihash) - integer, length, digest = multihash.unpack('CCA*') + integer, length, digest = multihash.unpack('CCa*') if length != digest.bytesize raise DigestLengthError, 'digest did not match expected multihash length' end