-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (60 loc) · 2.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
const bs58 = require('bs58');
const bananojs = require('@bananocoin/bananojs');
const bananoUtil = bananojs.bananoUtil;
const accountPrefix = 'ban_';
const cidB58Pattern = new RegExp('^Qm[0-9A-Za-z]{0,64}$');
const cidHexPattern = new RegExp('^1220[0-9A-Fa-f]{64}$');
const hexToBytes = bananoUtil.hexToBytes;
const getAccountPublicKey = bananoUtil.getAccountPublicKey;
const getAccount = (publicKey) => {
return bananoUtil.getAccount(publicKey, accountPrefix);
};
const validateIpfsCid = (ipfsCid) => {
if (typeof ipfsCid !== 'string') {
throw Error(`ipfs_cid expected to be string, got: ${typeof ipfsCid}`);
}
if (!cidB58Pattern.test(ipfsCid)) {
throw Error(`ipfs_cid:'${ipfsCid}' not valid v0 CID (Qm+base58)`);
}
};
const validateIpfsCidHex = (ipfsCidHex) => {
if (typeof ipfsCidHex !== 'string') {
throw Error(`ipfsCidHex expected to be string, got: ${typeof ipfsCidHex}`);
}
if (!cidHexPattern.test(ipfsCidHex)) {
throw Error(
`ipfsCidHex:'${ipfsCidHex}' not 64 hex chars after prefix 1220, ${ipfsCidHex.length}`,
);
}
};
/**
* Gets the IPFS CID encoded into a banano account.
* @memberof bananoIpfs
* @param {string} ipfsCid
* @return {string} ipfsAccount. A banano account with an IPFS CID encoded into the public key.
*/
const ifpsCidToAccount = (ipfsCid) => {
validateIpfsCid(ipfsCid);
const bytes = bs58.decode(ipfsCid);
const ipfsCidHex = Buffer.from(bytes).toString('hex');
validateIpfsCidHex(ipfsCidHex);
const ipfsPublicKey = ipfsCidHex.substring(4);
return getAccount(ipfsPublicKey);
};
/**
* Gets the IPFS CID encoded into a banano account.
* @memberof bananoIpfs
* @param {string} ipfsAccount A banano account with an IPFS CID encoded into the public key.
* @return {string} ipfsCid
*/
const accountToIpfsCid = (ipfsAccount) => {
const ipfsPublicKey = getAccountPublicKey(ipfsAccount);
const ipfsCidHex = `1220${ipfsPublicKey}`;
validateIpfsCidHex(ipfsCidHex);
const bytes = hexToBytes(ipfsCidHex);
const ipfsCid = bs58.encode(bytes);
validateIpfsCid(ipfsCid);
return ipfsCid;
};
module.exports = {ifpsCidToAccount, accountToIpfsCid, validateIpfsCidHex};