Beispiel #1
0
/***
 * Turn a multibase decoded string of bytes into a Cid struct
 * @param incoming the multibase decoded array
 * @param incoming_size the size of the array
 * @param cid the Cid structure to fill
 */
int ipfs_cid_cast(const unsigned char* incoming, size_t incoming_size, struct Cid* cid) {
	if (incoming_size == 34 && incoming[0] == 18 && incoming[1] == 32) {
		// this is a multihash
		cid->hash_length = mh_multihash_length(incoming, incoming_size);
		cid->codec = CID_PROTOBUF;
		cid->version = 0;

		mh_multihash_digest(incoming, incoming_size, &cid->hash, &cid->hash_length);
		return 1;
	}

	// This is not a multihash. Perhaps it is using varints. Try to peel the information out of the bytes.
	// first the version
	int pos = 0;
	size_t num_bytes = 0;
	cid->version = varint_decode(&incoming[pos], incoming_size - pos, &num_bytes);
	if (num_bytes == 0 || cid->version > 1 || cid->version < 0)
		return 0;
	pos = num_bytes;
	// now the codec
	uint32_t codec = 0;
	codec = varint_decode(&incoming[pos], incoming_size - pos, &num_bytes);
	if (num_bytes == 0)
		return 0;
	cid->codec = codec;
	pos += num_bytes;
	// now what is left
	cid->hash_length = incoming_size - pos;
	cid->hash = (unsigned char*)(&incoming[pos]);

	return 1;
}
static char *test_multihash_new_crafts_right_multihash(void) {
	int error;
	unsigned char buf[256]; // much bigger than needed
	size_t digest_len = -1;
	const unsigned char *digest = NULL;

	error = mh_multihash_digest(sha1_example, sha1_example_length,
		&digest, &digest_len);
	mu_assert("getting digest", error == MH_E_NO_ERROR);

	error = mh_new(buf, MH_H_SHA1, digest, digest_len);
	mu_assert("creating multihash", error == MH_E_NO_ERROR);

	mu_assert("crafted multihash is the same", memcmp(sha1_example, buf,
		sha1_example_length) == 0);

	return NULL;
}