forked from stakwork/sphinx-keysend-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signer.js
109 lines (99 loc) · 2.39 KB
/
signer.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
var grpc = require('grpc')
var ByteBuffer = require('bytebuffer')
var LND = require('./lightning')
const env = process.env.NODE_ENV || 'production'
const config = require(__dirname + '/config.json')[env]
var signerClient;
const loadSigner = () => {
if (signerClient) {
return signerClient
} else {
try {
var credentials = LND.loadCredentials('signer.macaroon')
var lnrpcDescriptor = grpc.load("proto/signer.proto");
var signer = lnrpcDescriptor.signrpc
signerClient = new signer.Signer(config.node_ip + ':' + config.lnd_port, credentials);
return signerClient
} catch (e) {
throw e
}
}
}
const signMessage = (msg) => {
return new Promise(async (resolve, reject) => {
let signer = await loadSigner()
try {
const options = {
msg: ByteBuffer.fromHex(msg),
key_loc: { key_family: 6, key_index: 0 },
}
signer.signMessage(options, function (err, sig) {
if (err || !sig.signature) {
reject(err)
} else {
const buf = ByteBuffer.wrap(sig.signature);
resolve(buf.toBase64())
}
})
} catch (e) {
reject(e)
}
})
}
async function signAscii(ascii) {
try {
const sig = await signMessage(ascii_to_hexa(ascii))
return sig
} catch (e) {
throw e
}
}
function ascii_to_hexa(str) {
var arr1 = [];
for (var n = 0, l = str.length; n < l; n++) {
var hex = Number(str.charCodeAt(n)).toString(16);
arr1.push(hex);
}
return arr1.join('');
}
async function verifyAscii(ascii,sig,pubkey) {
try {
const r = await verifyMessage(ascii_to_hexa(ascii),sig,pubkey)
return r
} catch(e) {
throw e
}
}
function verifyMessage(msg,sig,pubkey) {
return new Promise(async(resolve, reject)=> {
let signer = await loadSigner()
if(msg.length===0) {
return reject('invalid msg')
}
if(sig.length!==96) {
return reject('invalid sig')
}
if(pubkey.length!==66) {
return reject('invalid pubkey')
}
try {
const options = {
msg:ByteBuffer.fromHex(msg),
signature:ByteBuffer.fromBase64(sig),
pubkey:ByteBuffer.fromHex(pubkey),
}
signer.verifyMessage(options, function(err,res){
if(err) {
reject(err)
} else {
resolve(res)
}
})
} catch(e) {
reject(e)
}
})
}
module.exports={
signAscii, verifyAscii
}