-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprivilege-auth.mjs
353 lines (302 loc) · 12.7 KB
/
privilege-auth.mjs
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import * as secp from '@noble/secp256k1';
import secp256k1 from 'secp256k1';
import {createHash} from "node:crypto";
// IMPORTANT: requires Node 20+
// creating a random key pair
// you really may want to run this once, store your private and public keys being generated and use the below with these.
const pair = await createKeyPair();
// creating an authority as of token-auth described here https://github.com/BennyTheDev/tap-protocol-specs.
//
// auth ops must be inscribed and tapped (inscribe + sent to yourself) by the authority that wants to allow
// the use of specified tickers being handled by the authority (or empty message array for any token that the authority controls).
// after tapping, the specified tickers are associated with the account that tapped it.
//
// each hash must be unique. therefore the authority must provide a salt to make sure the resulting hash is unique.
// if your authority needs the capability to re-index and filter already signed auth creation ops,
// then the salt should be something unique like an inscription id that it refers to.
const authResult = await signAuth(
pair.pk,
pair.pub,
'auth',
{
'name' : 'Some privilege authority'
},
Math.random()
)
// generate a signed mint inscription text, ready for broadcasting
const mintResult = await signMint(
pair.pk,
pair.pub,
'randomtoken4',
1000,
'tb1pf9jluy2g797290uq5nutqm2yuynds6uf868ytc37nht53c5j8w3s7nfta7',
Math.random()
)
// generate a signed DMT mint inscription text, ready for broadcasting
const dmtMintResult = await signDmtMint(
pair.pk,
pair.pub,
'nat',
190002,
'825e287bb7dd163ed633110e31bc6abb6c80815ca68b7dd3cc71d729ecaaa3dci0',
false,
'tb1pf9jluy2g797290uq5nutqm2yuynds6uf868ytc37nht53c5j8w3s7nfta7',
Math.random()
)
const signVerificationResult = await signVerification(
pair.pk,
pair.pub,
'e349a9126a9476eb534457a7e78c748aeca67ec4d53fa9f0772408fb7233a9fei0',
'cea505f61f375ea2d8ea56f593e6b436f963753616c2095e755cb5ca4a6df85c',
'super collection',
111,
'tb1pltn4mqlpxxswxhmkj2ejdd0z98v74nr0xxdresvwvp5cyvctm0zs3m750l',
Math.random()
)
// creating a random pair for demonstration.
// in a production environment, the authority stores its private key at a safe place and signs
// the messages on demand.
console.log('####### RANDOM PAIR ########');
console.log(pair);
console.log('####### CREATE PRIVILEGE AUTH RESULT ########');
console.log(authResult);
console.log('####### CREATE MINT RESULT ########');
console.log(mintResult);
console.log('####### CREATE DMT MINT RESULT ########');
console.log(dmtMintResult);
console.log('####### CREATE VERIFICATION RESULT ########');
console.log(signVerificationResult);
/**
* Generates a random keypair
*
* @returns {Promise<{pk: string, pub: string}>}
*/
async function createKeyPair() {
let privKey;
do {
privKey = secp.utils.randomPrivateKey();
} while (!secp256k1.privateKeyVerify(privKey))
const pubKey = secp.getPublicKey(privKey);
return {
pk: Buffer.from(privKey).toString('hex'),
pub: Buffer.from(pubKey).toString('hex')
};
}
/**
* Creates an auth inscription op as signed inscription text
*
* @param privKey
* @param pubKey
* @param messageKey
* @param message
* @param salt
* @returns {Promise<{result: string, test: {valid: boolean, pubRecovered: string, pub: string}}>}
*/
async function signAuth(privKey, pubKey, messageKey, message, salt) {
privKey = Buffer.from(privKey, 'hex');
pubKey = Buffer.from(pubKey, 'hex');
let proto = {
p : 'tap',
op : 'privilege-auth',
sig: null,
hash : null,
salt : ''+salt
}
const msgHash = sha256(JSON.stringify(message) + proto.salt);
const signature = await secp.signAsync(msgHash, privKey);
proto[messageKey] = message;
proto.sig = { v : '' + signature.recovery, r : signature.r.toString(), s : signature.s.toString()};
proto.hash = Buffer.from(msgHash).toString('hex');
const test_proto = JSON.parse(JSON.stringify(proto));
const test_msgHash = sha256(JSON.stringify(test_proto[messageKey]) + test_proto.salt);
const isValid = secp.verify(signature, test_msgHash, pubKey);
let test = new secp.Signature(BigInt(proto.sig.r), BigInt(proto.sig.s), parseInt(proto.sig.v));
return {
test : {
valid : isValid,
pub : Buffer.from(pubKey).toString('hex'),
pubRecovered : test.recoverPublicKey(msgHash).toHex(),
compact_signature : test.toCompactHex().toLowerCase()
},
result : JSON.stringify(proto)
}
}
/**
* Creates and signs a mint inscription text for regular tap mints.
* Please note that instead of a random value, you might want to pass an incrementing number like a nonce.
* This is important if you intend to re-index your authority's indexer. This also means the authority has to store which message hash has been sent already and with which nonce.
* TAP indexers will ignoe existing message hashes as they are only valid once.
*
* @param privKey
* @param pubKey
* @param ticker
* @param amount
* @param salt
* @returns {Promise<{result: string, test: {valid: boolean, pubRecovered: string, pub: *}}>}
*/
async function signMint(privKey, pubKey, ticker, amount, address, salt, dta = null) {
privKey = Buffer.from(privKey, 'hex');
pubKey = Buffer.from(pubKey, 'hex');
let proto = {
p : 'tap',
op : 'token-mint',
tick : ticker,
amt : amount,
prv: {
sig : null,
hash : null,
address : address,
salt : ''+salt
}
}
if(dta !== null)
{
proto['dta'] = dta;
}
const msgHash = sha256(proto.p + '-' + proto.op + '-' + proto.tick + '-' + proto.amt + '-' + proto.prv.address + ( dta !== null ? '-' + dta : '' ) + '-' + proto.prv.salt);
const signature = await secp.signAsync(msgHash, privKey);
proto.prv.sig = { v : '' + signature.recovery, r : signature.r.toString(), s : signature.s.toString()};
proto.prv.hash = Buffer.from(msgHash).toString('hex');
const test_proto = JSON.parse(JSON.stringify(proto));
const test_msgHash = sha256(test_proto.p + '-' + test_proto.op + '-' + test_proto.tick + '-' + test_proto.amt + '-' + test_proto.prv.address + ( dta !== null ? '-' + dta : '' ) + '-' + test_proto.prv.salt);
const isValid = secp.verify(signature, test_msgHash, pubKey);
let test = new secp.Signature(BigInt(proto.prv.sig.r), BigInt(proto.prv.sig.s), parseInt(proto.prv.sig.v));
return {
test : {
valid : isValid,
pub : Buffer.from(pubKey).toString('hex'),
pubRecovered : test.recoverPublicKey(msgHash).toHex(),
compact_signature : test.toCompactHex().toLowerCase()
},
result : JSON.stringify(proto)
}
}
/**
* Creates and signs a mint inscription text for regular tap DMT mints.
* Please note that instead of a random value, you might want to pass an incrementing number like a nonce.
* This is important if you intend to re-index your authority's indexer. This also means the authority has to store which message hash has been sent already and with which nonce.
* TAP indexers will ignore existing message hashes as they are only valid once.
*
* Use is_blockdrop true/false to signal this is a blockdrop mint. If set to true, no dep field will be generated but you still will have to pass the deployment inscription id for signing the hash.
*
* @param privKey
* @param pubKey
* @param ticker
* @param block
* @param deployment
* @param is_blockdrop
* @param salt
* @returns {Promise<{result: string, test: {valid: boolean, pubRecovered: string, pub: *}}>}
*/
async function signDmtMint(privKey, pubKey, ticker, block, deployment, is_blockdrop, address, salt, dta = null) {
privKey = Buffer.from(privKey, 'hex');
pubKey = Buffer.from(pubKey, 'hex');
let proto = {
p : 'tap',
op : 'dmt-mint',
tick : ticker.toLowerCase(),
blk : block,
dep : deployment,
prv: {
sig : null,
hash : null,
address : address,
salt : ''+salt
}
}
if(is_blockdrop)
{
delete proto.dep;
}
if(dta !== null)
{
proto['dta'] = dta;
}
const msgHash = sha256(proto.p + '-' + proto.op + '-' + proto.tick + '-' + proto.blk + '-' + deployment + '-' + proto.prv.address + ( dta !== null ? '-' + dta : '' ) + '-' + proto.prv.salt);
const signature = await secp.signAsync(msgHash, privKey);
proto.prv.sig = { v : '' + signature.recovery, r : signature.r.toString(), s : signature.s.toString()};
proto.prv.hash = Buffer.from(msgHash).toString('hex');
const test_proto = JSON.parse(JSON.stringify(proto));
const test_msgHash = sha256(test_proto.p + '-' + test_proto.op + '-' + test_proto.tick + '-' + test_proto.blk + '-' + deployment + '-' + test_proto.prv.address + ( dta !== null ? '-' + dta : '' ) + '-' + test_proto.prv.salt);
const isValid = secp.verify(signature, test_msgHash, pubKey);
let test = new secp.Signature(BigInt(proto.prv.sig.r), BigInt(proto.prv.sig.s), parseInt(proto.prv.sig.v));
return {
test : {
valid : isValid,
pub : Buffer.from(pubKey).toString('hex'),
pubRecovered : test.recoverPublicKey(msgHash).toHex(),
compact_signature : test.toCompactHex().toLowerCase()
},
result : JSON.stringify(proto)
}
}
/**
* Create signed inscription texts for general-purpose file hashes (sha256).
* These types of inscriptions enable authorities to verify file hashes of any file type like images, videos, etc.
* The inscriptions can be traded or being used to track valid assets (for example valid ordinals).
*
* By inscribing a signed verification, the address given owns the provenance and can use the tap protocol to prove that an authority granted its privilege.
* An authority should either be the issuer of the files or acts in the issuer's behalf.
* Therefore, an issuer should point to the ordinals id of the authority through offchain methods (socials, project website, chats, etc).
*
* Since this is a collection driven approach, a collection name and a sequence have to be passed.
* The collection name may consist of up to 512 symbols (as of unicode).
* The sequence must be an unsigned integer and may be arbitrary but not larger than 9007199254740991.
* It is recommended to use the sequence number for collectible IDs. If every hash being issued is unique, simply set it to 0.
* If your hashes are NOT unique, you have to assign different sequence numbers,
* otherwise the tap protocol considers duplicates as processed.
*
* If you verify the content of existing ordinals, you may consider to use their ordinals ids (not the ordinals number) as salt.
*
* @param privKey
* @param pubKey
* @param privilege_authority_id
* @param sha256_hash
* @param collection
* @param sequence
* @param address
* @param salt
* @returns {Promise<{result: string, test: {valid: boolean, pubRecovered: string, pub: *}}>}
*/
async function signVerification(privKey, pubKey, privilege_authority_id, sha256_hash, collection, sequence, address, salt) {
privKey = Buffer.from(privKey, 'hex');
pubKey = Buffer.from(pubKey, 'hex');
let proto = {
p : 'tap',
op : 'privilege-auth',
sig : null,
hash : null,
address : address,
salt : ''+salt,
prv : privilege_authority_id,
verify : sha256_hash,
col : collection,
seq : sequence
}
const msgHash = sha256(proto.prv + '-' + proto.col + '-' + proto.verify + '-' + proto.seq + '-' + proto.address + '-' + proto.salt);
const signature = await secp.signAsync(msgHash, privKey);
proto.sig = { v : '' + signature.recovery, r : signature.r.toString(), s : signature.s.toString()};
proto.hash = Buffer.from(msgHash).toString('hex');
const test_proto = JSON.parse(JSON.stringify(proto));
const test_msgHash = sha256(test_proto.prv + '-' + test_proto.col + '-' + test_proto.verify + '-' + test_proto.seq + '-' + test_proto.address + '-' + test_proto.salt);
const isValid = secp.verify(signature, test_msgHash, pubKey);
let test = new secp.Signature(BigInt(proto.sig.r), BigInt(proto.sig.s), parseInt(proto.sig.v));
return {
test : {
valid : isValid,
pub : Buffer.from(pubKey).toString('hex'),
pubRecovered : test.recoverPublicKey(msgHash).toHex(),
compact_signature : test.toCompactHex().toLowerCase()
},
result : JSON.stringify(proto)
}
}
/**
* Creates a buffered hash from given content.
*
* @param content
* @returns {Buffer}
*/
function sha256(content) {
return createHash('sha256').update(content).digest();
}