-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
95 lines (78 loc) · 2.2 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import secp256k1 from 'secp256k1';
import { randomBytes } from 'crypto';
import createHash from 'sha.js';
import axios from 'axios';
// Needed for send
function hashTx(tx) {
let txBytes = JSON.stringify(tx);
let txHash = createHash('sha256')
.update(txBytes)
.digest();
return txHash;
}
function signTx(privKey, tx) {
let txHash = hashTx(tx);
let data = Object.assign({}, tx);
const {signature} = secp256k1.sign(txHash, privKey);
return {data, signature};
}
function generateAddress(privateKey) {
return secp256k1.publicKeyCreate(privateKey);
}
async function getBalance(lotionUrl, address) {
let { data } = await axios.get(lotionUrl + '/state');
return data.balances[address] || 0;
}
async function send(lotionUrl, privKey, obj) {
console.log(obj)
let txx = {
amount: obj.amount,
from: generateAddress(privKey),
to: obj.address,
org: obj.org,
feePortion: obj.feePortion
};
let tx = signTx(privKey, txx);
let result = await axios.post(lotionUrl + '/txs', tx);
console.log(result.data)
return result.data;
}
async function getTransactions(lotionUrl) {
let result = await axios.get(lotionUrl + '/state');
return result.data;
}
class Fungus {
constructor({ lotionUrl }) {
this.lotionUrl = lotionUrl;
}
generatePrivateKey() {
let privKey;
do {
privKey = randomBytes(32);
} while (!secp256k1.privateKeyVerify(privKey));
return privKey;
}
generateStaticPrivateKey(num=1) {
// for demo
if(typeof num !== 'number') return '';
let privKey;
do {
privKey = Buffer.alloc(32);
for(let i = 0; i < privKey.length; i++) privKey[i] = num
} while (!secp256k1.privateKeyVerify(privKey));
return privKey;
}
generateAddress(privateKey) {
return generateAddress(privateKey);
}
getBalance(address) {
return getBalance(this.lotionUrl, address);
}
createTransaction(privKey, obj) {
return send(this.lotionUrl, privKey, obj);
}
getAllTransactions() {
return getTransactions(this.lotionUrl);
}
}
export default Fungus;