psf-multisig-approval 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,211 @@
1
1
  # psf-multisig-approval
2
2
 
3
- This is an npm library for node.js. It implements the [PS009 specification for multisignature approval](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval.md).
3
+ This is an npm library for node.js. It implements the [PS009 specification for multisignature approval](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval.md). The main consumers of this library of [psf-bch-wallet](https://github.com/Permissionless-Software-Foundation/psf-bch-wallet) and [ipfs-p2wdb-service](https://github.com/Permissionless-Software-Foundation/ipfs-p2wdb-service).
4
+
5
+ ## Instancing Library
6
+ This library depends on [minimal-slp-wallet](https://www.npmjs.com/package/minimal-slp-wallet). An instance of that library is expected to be injected into this this one when instantiated. Here is an example:
7
+
8
+ ```javascript
9
+ const SlpWallet = require('minimal-slp-wallet')
10
+ const MultisigApproval = require('psf-multisig-approval')
11
+
12
+ async function start() {
13
+ // Instance the BCH wallet
14
+ const wallet = new SlpWallet(undefined, {
15
+ interface: 'consumer-api',
16
+ restURL: 'https://free-bch.fullstack.cash'
17
+ })
18
+ await wallet.initialize()
19
+
20
+ // Instance this library
21
+ const ps009 = new MultisigApproval({wallet})
22
+ }
23
+ start()
24
+ ```
25
+
26
+ ## Get NFT Holder Information
27
+ PS009 uses NFTs as 'homing beacons'. It generates a multisignature wallet from the public keys of the NFT holders. Finding the addresses and public keys of the NFT holders is a foundational feature of the protocol. All NFTs are connected by the Group Token ID that generated them.
28
+
29
+ If the holder of the NFT has not made any transactions, then their public key will not be on the blockchain. In that case, the NFT and address will be added to the `keysNotFound` array. Those holders will not be included in the multisignature wallet.
30
+
31
+ ```javascript
32
+ const groupTokenId = '8e8d90ebdb1791d58eba7acd428ff3b1e21c47fb7aba2ba3b5b815aa0fe7d6d5'
33
+
34
+ const result = await ps009.getNftHolderInfo(groupTokenId)
35
+ console.log(result)
36
+
37
+ /*
38
+ {
39
+ keys: [
40
+ {
41
+ addr: 'bitcoincash:qz4zsa22glal5c4jqm748xge657gwuw2d5t9nvg64p',
42
+ pubKey: '021ca211a04a1d489ae77e01c28c97b02e733893890fda00a359ca8956c2e0d259',
43
+ nft: 'e86164aaa06efac1d6453951f67beafe042f0bceb9312845a95355b1e93aa846'
44
+ },
45
+ {
46
+ addr: 'bitcoincash:qpfvh07mdt7yq5czndaz5qq4g9q3m87qpspy7xaxgu',
47
+ pubKey: '0361fd21512b9072e8f6b984d9b04c57e5779867c2ad002999372268770fcb2674',
48
+ nft: 'da7ccbd5e24e468c9e7402489ca9148b5e76e588b73cc4aa4bbf1ca41d5808ab'
49
+ },
50
+ {
51
+ addr: 'bitcoincash:qpsxtzaa7rg677akcc2znpenpsy5jr2ygywmfd45p2',
52
+ pubKey: '03b9bdc40c478ab0536be29c368b26c48a5e8d6867fc34b77c727ab690365aae91',
53
+ nft: '0ec318bede8c2f229db840a24cb63d662ad91e8e6c840e46e6a8ff2d173049ce'
54
+ },
55
+ {
56
+ addr: 'bitcoincash:qqk3aczzggvxnfm7rwm0f9yz20yr00dmpv2f3tasdr',
57
+ pubKey: '033c930d4cff4ba68a70f7a21443e20ad4176173380d21f8c3ce27f7ce947f3246',
58
+ nft: '51624e772adafd7c6a9da38774e4f654282199bd5402e049ee087fc2bd900882'
59
+ },
60
+ {
61
+ addr: 'bitcoincash:qpszha37cjn6n83hpxn7zz5ndaa35vygtcgslxhpuc',
62
+ pubKey: '024be54accec310c2636140336ae548d610ba9b7ce300b3f42494b4a6f2963731f',
63
+ nft: 'e70cc72eeb15c82e96b1f8127d3b138b2fc8ea101fe9c62302ec641c05d4b97d'
64
+ }
65
+ ],
66
+ keysNotFound: []
67
+ }
68
+ */
69
+ ```
70
+
71
+ ## Get an Approval Transaction
72
+ This function will take a BCH address as input. It will search the transaction history for the address, and will return an object about the first `APPROVAL` transaction that it finds. If it can't find one, it will return null.
73
+
74
+ ```javascript
75
+ const address = 'bitcoincash:qrwe6kxhvu47ve6jvgrf2d93w0q38av7s5xm9xfehr'
76
+
77
+ const result = await ps009.getApprovalTx({address})
78
+ console.log(result)
79
+
80
+ /*
81
+ {
82
+ approvalTxid: 'a63f9fbcc901316e6e89f5a8caaad6b2ab268278b29866c6c22088bd3ab93900',
83
+ updateTxid: 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f',
84
+ approvalTxDetails: {
85
+ txid: 'a63f9fbcc901316e6e89f5a8caaad6b2ab268278b29866c6c22088bd3ab93900',
86
+ vin: [ [Object] ],
87
+ vout: [ [Object], [Object], [Object] ],
88
+ ...
89
+ isValidSlp: false
90
+ },
91
+ opReturn: 'j\x07APPROVE@f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f'
92
+ }
93
+ */
94
+ ```
95
+
96
+ ## Get an Update Transaction
97
+
98
+ An *approval* transaction will point to an *update* transaction with its OP_RETURN output. This function is used to retrieve and decode that update transaction. Given a TXID, it will return details from the transaction, including the IPFS CID and timestamp stored in the update transactions OP_RETURN output.
99
+
100
+ ```javascript
101
+ const txid = 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f'
102
+
103
+ const result = await uut.getUpdateTx({ txid })
104
+ console.log(result)
105
+
106
+ /*
107
+ {
108
+ cid: 'bafybeib5d6s6t3tq4lhwp2ocvz7y2ws4czgkrmhlhv5y5aeyh6bqrmsxxi',
109
+ ts: 1676560247168,
110
+ txid: 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f',
111
+ txDetails: {
112
+ txid: 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f',
113
+ hash: 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f',
114
+ vin: [ [Object] ],
115
+ vout: [ [Object], [Object], [Object], [Object] ],
116
+ ...
117
+ isValidSlp: false
118
+ }
119
+ }
120
+
121
+ */
122
+ ```
123
+
124
+ ## Get IPFS CID Data
125
+
126
+ The update transaction will reference an IPFS CID. That data will need to be retrieved from an IPFS gateway. The default gateway can be overwritten when this library is instantiated.
127
+
128
+ ```javascript
129
+ // Instance this library and overwrite the default IPFS gateway
130
+ const ps009 = new MultisigApproval({
131
+ wallet,
132
+ ipfsGateway: 'https://p2wdb-gateway-678.fullstack.cash'
133
+ })
134
+
135
+ const cid = 'bafybeib5d6s6t3tq4lhwp2ocvz7y2ws4czgkrmhlhv5y5aeyh6bqrmsxxi'
136
+
137
+ const updateData = await ps009.getCidData({cid})
138
+ console.log(updateData)
139
+
140
+ /*
141
+ {
142
+ groupId: '8e8d90ebdb1791d58eba7acd428ff3b1e21c47fb7aba2ba3b5b815aa0fe7d6d5',
143
+ keys: [
144
+ {
145
+ addr: 'bitcoincash:qz4zsa22glal5c4jqm748xge657gwuw2d5t9nvg64p',
146
+ pubKey: '021ca211a04a1d489ae77e01c28c97b02e733893890fda00a359ca8956c2e0d259',
147
+ nft: 'e86164aaa06efac1d6453951f67beafe042f0bceb9312845a95355b1e93aa846'
148
+ },
149
+ {
150
+ addr: 'bitcoincash:qpfvh07mdt7yq5czndaz5qq4g9q3m87qpspy7xaxgu',
151
+ pubKey: '0361fd21512b9072e8f6b984d9b04c57e5779867c2ad002999372268770fcb2674',
152
+ nft: 'da7ccbd5e24e468c9e7402489ca9148b5e76e588b73cc4aa4bbf1ca41d5808ab'
153
+ },
154
+ {
155
+ addr: 'bitcoincash:qpsxtzaa7rg677akcc2znpenpsy5jr2ygywmfd45p2',
156
+ pubKey: '03b9bdc40c478ab0536be29c368b26c48a5e8d6867fc34b77c727ab690365aae91',
157
+ nft: '0ec318bede8c2f229db840a24cb63d662ad91e8e6c840e46e6a8ff2d173049ce'
158
+ },
159
+ {
160
+ addr: 'bitcoincash:qqk3aczzggvxnfm7rwm0f9yz20yr00dmpv2f3tasdr',
161
+ pubKey: '033c930d4cff4ba68a70f7a21443e20ad4176173380d21f8c3ce27f7ce947f3246',
162
+ nft: '51624e772adafd7c6a9da38774e4f654282199bd5402e049ee087fc2bd900882'
163
+ },
164
+ {
165
+ addr: 'bitcoincash:qpszha37cjn6n83hpxn7zz5ndaa35vygtcgslxhpuc',
166
+ pubKey: '024be54accec310c2636140336ae548d610ba9b7ce300b3f42494b4a6f2963731f',
167
+ nft: 'e70cc72eeb15c82e96b1f8127d3b138b2fc8ea101fe9c62302ec641c05d4b97d'
168
+ }
169
+ ],
170
+ walletObj: {
171
+ address: 'bitcoincash:pqntzt6wcp38h8ud68wjnwh437uek76lhvhlwcm4fj',
172
+ scriptHex: 'a91426b12f4ec0627b9f8dd1dd29baf58fb99b7b5fbb87',
173
+ publicKeys: [
174
+ '021ca211a04a1d489ae77e01c28c97b02e733893890fda00a359ca8956c2e0d259',
175
+ '0361fd21512b9072e8f6b984d9b04c57e5779867c2ad002999372268770fcb2674',
176
+ '03b9bdc40c478ab0536be29c368b26c48a5e8d6867fc34b77c727ab690365aae91',
177
+ '033c930d4cff4ba68a70f7a21443e20ad4176173380d21f8c3ce27f7ce947f3246',
178
+ '024be54accec310c2636140336ae548d610ba9b7ce300b3f42494b4a6f2963731f'
179
+ ],
180
+ requiredSigners: 3
181
+ },
182
+ multisigAddr: 'bitcoincash:pqntzt6wcp38h8ud68wjnwh437uek76lhvhlwcm4fj',
183
+ p2wdbWritePrice: 0.08335233
184
+ }
185
+ */
186
+ ```
187
+
188
+ ## Validate an Approval Transaction
189
+ After data about the approval and update transactions have been retrieved, it's important to validate that the approval transaction is valid and has not been faked. This function will return either `true` or `false` depending on the result of testing the transaction validity.
190
+
191
+ ```javascript
192
+ const address = 'bitcoincash:qrwe6kxhvu47ve6jvgrf2d93w0q38av7s5xm9xfehr'
193
+ const approvalObj = await ps009.getApprovalTx({ address })
194
+
195
+ const txid = 'f8ea1fcd4481adfd62c6251c6a4f63f3d5ac3d5fdcc38b350d321d93254df65f'
196
+ const updateObj = await ps009.getUpdateTx({ txid })
197
+
198
+ const cid = 'bafybeib5d6s6t3tq4lhwp2ocvz7y2ws4czgkrmhlhv5y5aeyh6bqrmsxxi'
199
+ const updateData = await ps009.getCidData({ cid })
200
+
201
+ const inObj = { approvalObj, updateObj, updateData }
202
+ const result = await ps009.validateApproval(inObj)
203
+ console.log(result)
204
+
205
+ /*
206
+ true
207
+ */
208
+ ```
4
209
 
5
210
  # License
6
211
  [MIT](LICENSE.md)
package/index.js CHANGED
@@ -3,24 +3,325 @@
3
3
  https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval.md
4
4
  */
5
5
 
6
- /* eslint-disable no-async-promise-executor */
6
+ // global libraries
7
+ const bitcore = require('bitcore-lib-cash')
8
+ const axios = require('axios')
7
9
 
8
- 'use strict'
10
+ // Local libraries
11
+ const NFTs = require('./lib/nfts')
12
+ const UtilLib = require('./lib/util')
9
13
 
10
- const BCHJS = require('@psf/bch-js')
14
+ class MultisigApproval {
15
+ constructor (localConfig = {}) {
16
+ // Dependency Injection
17
+ this.wallet = localConfig.wallet
18
+ if (!this.wallet) {
19
+ throw new Error('Instance of minimal-slp-wallet must be passed in as a property called \'wallet\', when initializing the psf-multisig-approval library.')
20
+ }
11
21
 
12
- const Util = require('./lib/util')
13
- const util = new Util()
22
+ // The default IPFS gateway can be overwritten by the user when this library
23
+ // is instantiated.
24
+ this.ipfsGateway = localConfig.ipfsGateway
25
+ if (!this.ipfsGateway) {
26
+ this.ipfsGateway = 'https://p2wdb-gateway-678.fullstack.cash'
27
+ }
14
28
 
15
- let _this // local global for 'this'.
29
+ // Encapsulate dependencies
30
+ this.bchjs = this.wallet.bchjs
31
+ this.bitcore = bitcore
32
+ this.axios = axios
33
+ this.nfts = new NFTs(localConfig)
34
+ this.util = new UtilLib(localConfig)
16
35
 
17
- class BoilplateLib {
18
- constructor () {
19
- _this = this
36
+ // Bind the this object to all subfunctions in this class
37
+ this.getNftHolderInfo = this.getNftHolderInfo.bind(this)
38
+ this.createMultisigAddress = this.createMultisigAddress.bind(this)
39
+ this.getApprovalTx = this.getApprovalTx.bind(this)
20
40
 
21
- _this.bchjs = new BCHJS()
22
- _this.util = util
41
+ // Create a transaction details cache, to reduce the number of API calls.
42
+ this.txCache = {}
43
+ }
44
+
45
+ // This function retrieves the NFTs associated with a Group token ID. It then
46
+ // tries to retrieve the BCH addresses and public keys of the holders of those
47
+ // NFTs. It returns an object with all that information in it.
48
+ // The function defaults to the PSF Minting Council, but any Group token ID
49
+ // can be used.
50
+ async getNftHolderInfo (groupTokenId = '8e8d90ebdb1791d58eba7acd428ff3b1e21c47fb7aba2ba3b5b815aa0fe7d6d5') {
51
+ try {
52
+ // console.log('groupTokenId: ', groupTokenId)
53
+
54
+ const nfts = await this.nfts.getNftsFromGroup()
55
+
56
+ const addrs = await this.nfts.getAddrsFromNfts(nfts)
57
+
58
+ const { keys, keysNotFound } = await this.nfts.findKeys(addrs, nfts)
59
+
60
+ return { keys, keysNotFound }
61
+ } catch (err) {
62
+ console.error('Error in getNftHolderInfo()')
63
+ throw err
64
+ }
65
+ }
66
+
67
+ // Generate a P2SH multisignature wallet from the public keys of the NFT holders.
68
+ // The address for the wallet is returned.
69
+ // The input for this function should be the `keys` output from
70
+ // getNftHolderInfo()
71
+ createMultisigAddress (inObj = {}) {
72
+ try {
73
+ const { keys } = inObj
74
+ let requiredSigners = inObj.requiredSigners
75
+
76
+ // Input validation
77
+ if (!Array.isArray(keys)) {
78
+ throw new Error('keys must be an array containing public keys')
79
+ }
80
+
81
+ // Isolate just an array of public keys.
82
+ const pubKeys = []
83
+ for (let i = 0; i < keys.length; i++) {
84
+ const thisPair = keys[i]
85
+
86
+ pubKeys.push(thisPair.pubKey)
87
+ }
88
+
89
+ // If the number of required signers is not specified, then default to
90
+ // a 50% + 1 threashold.
91
+ if (!requiredSigners) {
92
+ requiredSigners = Math.floor(pubKeys.length / 2) + 1
93
+ }
94
+
95
+ // Multisig Address
96
+ const msAddr = new bitcore.Address(pubKeys, requiredSigners)
97
+
98
+ // Locking Script in hex representation.
99
+ const scriptHex = new bitcore.Script(msAddr).toHex()
100
+
101
+ const walletObj = {
102
+ address: msAddr.toString(),
103
+ scriptHex,
104
+ publicKeys: pubKeys,
105
+ requiredSigners
106
+ }
107
+
108
+ return walletObj
109
+ } catch (err) {
110
+ console.error('Error in createMultisigWallet()')
111
+ throw err
112
+ }
113
+ }
114
+
115
+ // Given a BCH address, scan its transaction history to find the latest
116
+ // APPROVAL transaction. This function returns the TXID of the UPDATE
117
+ // transaction that the APPROVAL transaction approves.
118
+ // If no APPROVAL transaction can be found, then function returns null.
119
+ // An optional input, filterTxids, is an array of transaction IDs to ignore. This can
120
+ // be used to ignore/skip any known, fake approval transactions.
121
+ async getApprovalTx (inObj = {}) {
122
+ try {
123
+ let address = inObj.address
124
+ const { filterTxids } = inObj
125
+
126
+ // Input validation
127
+ if (address.includes('simpleledger:')) {
128
+ address = this.bchjs.SLP.Address.toCashAddress(address)
129
+ }
130
+ if (!address.includes('bitcoincash:')) {
131
+ throw new Error('Input address must start with bitcoincash: or simpleledger:')
132
+ }
133
+
134
+ // Get the transaction history for the address
135
+ const txHistory = await this.wallet.getTransactions(address)
136
+ // console.log('txHistory: ', JSON.stringify(txHistory, null, 2))
137
+
138
+ // Loop through the transaction history
139
+ for (let i = 0; i < txHistory.length; i++) {
140
+ const thisTxid = txHistory[i]
141
+
142
+ // const height = thisTxid.height
143
+ const txid = thisTxid.tx_hash
144
+
145
+ // Skip the txid if it is in the filter list.
146
+ if (Array.isArray(filterTxids)) {
147
+ const txidFound = filterTxids.find(x => x === txid)
148
+ // console.log('txidFound: ', txidFound)
149
+ if (txidFound) {
150
+ continue
151
+ }
152
+ }
153
+
154
+ // Get the transaction details for the transaction
155
+ const txDetails = await this.util.getTxData(txid)
156
+ // console.log('txDetails: ', JSON.stringify(txDetails, null, 2))
157
+ // console.log(`txid: ${txid}`)
158
+
159
+ const out2ascii = Buffer.from(txDetails.vout[0].scriptPubKey.hex, 'hex').toString('ascii')
160
+ // console.log('out2ascii: ', out2ascii)
161
+
162
+ // If the first output is not an OP_RETURN, then the tx can be discarded.
163
+ if (!out2ascii.includes('APPROVE')) {
164
+ continue
165
+ }
166
+
167
+ const updateTxid = out2ascii.slice(10)
168
+ // console.log('updateTxid: ', updateTxid)
169
+
170
+ const outObj = {
171
+ approvalTxid: txid,
172
+ updateTxid,
173
+ approvalTxDetails: txDetails,
174
+ opReturn: out2ascii
175
+ }
176
+
177
+ return outObj
178
+ }
179
+
180
+ return null
181
+ } catch (err) {
182
+ console.error('Error in getApprovedData()')
183
+ throw err
184
+ }
185
+ }
186
+
187
+ // This function will retrieve an update transaction, given its txid. It will
188
+ // return an object with data about the transaction, including the CID and
189
+ // timestamp values encoded in the transactions OP_RETURN.
190
+ async getUpdateTx (inObj = {}) {
191
+ try {
192
+ const { txid } = inObj
193
+
194
+ // Input validation
195
+ if (!txid) {
196
+ throw new Error('txid required')
197
+ }
198
+
199
+ // Get the transaction details for the transaction
200
+ const txDetails = await this.util.getTxData(txid)
201
+ // console.log('txDetails: ', JSON.stringify(txDetails, null, 2))
202
+ // console.log(`txid: ${txid}`)
203
+
204
+ let updateObj = {}
205
+ try {
206
+ const out2ascii = Buffer.from(txDetails.vout[0].scriptPubKey.hex, 'hex').toString('ascii')
207
+ // console.log('out2ascii: ', out2ascii)
208
+
209
+ const jsonStr = out2ascii.slice(4)
210
+ // console.log('jsonStr: ', jsonStr)
211
+
212
+ updateObj = JSON.parse(jsonStr)
213
+ } catch (err) {
214
+ throw new Error('Could not parse JSON inside the transaction')
215
+ }
216
+
217
+ updateObj.txid = txid
218
+ updateObj.txDetails = txDetails
219
+
220
+ return updateObj
221
+ } catch (err) {
222
+ console.error('Error in getUpdateTx()')
223
+ throw err
224
+ }
225
+ }
226
+
227
+ // Given an CID, this function will retrieve the update data from an IPFS
228
+ // gateway.
229
+ async getCidData (inObj = {}) {
230
+ try {
231
+ const { cid } = inObj
232
+
233
+ // Input validation
234
+ if (!cid) {
235
+ throw new Error('cid a required input')
236
+ }
237
+
238
+ const urlStr = `${this.ipfsGateway}/ipfs/${cid}/data.json`
239
+ // console.log('urlStr: ', urlStr)
240
+
241
+ const request = await this.axios.get(urlStr)
242
+
243
+ return request.data
244
+ } catch (err) {
245
+ console.error('Error in getCidData()')
246
+ throw err
247
+ }
248
+ }
249
+
250
+ // This function will validate the approval transaction.
251
+ // This function will return true or false, to indicate the validity of the
252
+ // approval transaction.
253
+ // The input to this function is the output of several of the above function:
254
+ // - approvalObj is the output of getApprovalTx()
255
+ // - updateObj is the output of getUpdateTx()
256
+ // - updateData is the IPFS CID data retrieved with getCidData()
257
+ // - groupTokenId is optional. If not specified, it will default to the Group
258
+ // token used to generate the PSF Minting Council NFTs.
259
+ async validateApproval (inObj = {}) {
260
+ try {
261
+ // console.log('inObj: ', JSON.stringify(inObj, null, 2))
262
+
263
+ const { approvalObj, updateObj, updateData, groupTokenId } = inObj
264
+
265
+ let validationResult = false
266
+
267
+ // Input validation
268
+ if (!approvalObj) {
269
+ throw new Error('Output object of getApprovalTx() is expected as input to this function, as \'approvalObj\'')
270
+ }
271
+ if (!updateObj) {
272
+ throw new Error('Output object of getUpdateTx() is expected as input to this function, as \'updateObj\'')
273
+ }
274
+ if (!updateData) {
275
+ throw new Error('Update CID JSON data is expected as input to this function, as \'updateData\'')
276
+ }
277
+
278
+ // Regenerate the multisig address from the pubkeys in the update data.
279
+ // Ensure it matches the input address to the approval transaction.
280
+ const pubKeys = updateData.walletObj.publicKeys
281
+ const requiredSigners = updateData.walletObj.requiredSigners
282
+ const approvalInputAddr = approvalObj.approvalTxDetails.vin[0].address
283
+ const msAddr = new this.bitcore.Address(pubKeys, requiredSigners).toString()
284
+ if (msAddr !== approvalInputAddr) {
285
+ console.log(`Approval TX input address (${approvalInputAddr}) does not match calculated multisig address ${msAddr}`)
286
+ return validationResult
287
+ }
288
+
289
+ // Get public key data for each NFT holder, from the blockchain.
290
+ const nftData = await this.getNftHolderInfo(groupTokenId)
291
+ const tokenPubKeys = nftData.keys
292
+
293
+ // Loop through the public keys from the token data, and count the matches.
294
+ let matches = 0
295
+ for (let i = 0; i < tokenPubKeys.length; i++) {
296
+ const thisTokenPubKey = tokenPubKeys[i].pubKey
297
+
298
+ // Loop through the public keys from the update data
299
+ for (let j = 0; j < pubKeys.length; j++) {
300
+ const thisUpdatePubKey = pubKeys[j]
301
+
302
+ if (thisTokenPubKey === thisUpdatePubKey) {
303
+ matches++
304
+ break
305
+ }
306
+ }
307
+ }
308
+
309
+ // Set a threshold for success.
310
+ let threshold = 2 // Minimum
311
+ if (requiredSigners > threshold) threshold = requiredSigners
312
+
313
+ // If the threshold of public keys match, then the approval transaction
314
+ // has been validated.
315
+ if (matches >= threshold) {
316
+ validationResult = true
317
+ }
318
+
319
+ return validationResult
320
+ } catch (err) {
321
+ console.error('Error in validateApproval()')
322
+ throw err
323
+ }
23
324
  }
24
325
  }
25
326
 
26
- module.exports = BoilplateLib
327
+ module.exports = MultisigApproval
package/lib/nfts.js ADDED
@@ -0,0 +1,106 @@
1
+ /*
2
+ This library contains code for handling NFT and Group SLP tokens. Specifically
3
+ it has functions around looking up the NFTs related to a Group token, then
4
+ retrieving data on the holders of those NFTs.
5
+ */
6
+
7
+ class NFTs {
8
+ constructor (localConfig = {}) {
9
+ this.wallet = localConfig.wallet
10
+ if (!this.wallet) {
11
+ throw new Error('Instance of minimal-slp-wallet must be passed in as a property called \'wallet\', when initializing the nfts.js library.')
12
+ }
13
+ }
14
+
15
+ // Retrieve a list of NFTs from the Group token that spawned them.
16
+ // The default value is the PSF Minting Council Group token.
17
+ async getNftsFromGroup (groupId = '8e8d90ebdb1791d58eba7acd428ff3b1e21c47fb7aba2ba3b5b815aa0fe7d6d5') {
18
+ try {
19
+ const groupData = await this.wallet.getTokenData(groupId)
20
+ // console.log('groupData: ', groupData)
21
+
22
+ const nfts = groupData.genesisData.nfts
23
+
24
+ return nfts
25
+ } catch (err) {
26
+ console.error('Error in getNftsFromGroup()')
27
+ throw err
28
+ }
29
+ }
30
+
31
+ // This function expects an array of strings as input. Each element in the
32
+ // input array is expected to be the Token ID of the an NFT. The address
33
+ // holding each NFT is looked up on the blockchain. The array of returned
34
+ // addresses are filtered for duplicates, before being returned.
35
+ async getAddrsFromNfts (nfts = []) {
36
+ try {
37
+ let addrs = []
38
+
39
+ // Loop through each NFT Token ID in the array.
40
+ for (let i = 0; i < nfts.length; i++) {
41
+ const thisNft = nfts[i]
42
+
43
+ const nftData = await this.wallet.getTokenData(thisNft, true)
44
+ // console.log('nftData: ', nftData)
45
+
46
+ addrs.push(nftData.genesisData.nftHolder)
47
+ }
48
+
49
+ // Remove duplicate addresses
50
+ addrs = [...new Set(addrs)]
51
+
52
+ return addrs
53
+ } catch (err) {
54
+ console.error('Error in getAddrsFromNfts(): ', err)
55
+ throw err
56
+ }
57
+ }
58
+
59
+ // The input to this function is the output of getNftsFromGroup() and
60
+ // getAddrsFromNfts(). It expects two arrays of strings, one an array of
61
+ // NFT Token IDs, the other an array of addresses holding those NFTs.
62
+ //
63
+ // For each address, it attempts to lookup the public key for that address.
64
+ // It returns an object with a keys and keysNotFound property:
65
+ // - keys - Object containing address and public key
66
+ // - keysNotFound - Array of addresses whos public keys could not be found.
67
+ async findKeys (addrs, nfts) {
68
+ // It is assumed that element 1 in the addrs array is associated with
69
+ // element 1 in the nfts array.
70
+
71
+ try {
72
+ const keys = []
73
+ const keysNotFound = []
74
+
75
+ for (let i = 0; i < addrs.length; i++) {
76
+ const thisAddr = addrs[i]
77
+ const thisNft = nfts[i]
78
+
79
+ // console.log('this.wallet: ', this.wallet)
80
+ // console.log('this.wallet.interface: ', this.wallet.interface)
81
+ // console.log('this.wallet.restURL: ', this.wallet.restURL)
82
+
83
+ // Get public Key for reciever from the blockchain.
84
+ const publicKey = await this.wallet.getPubKey(thisAddr)
85
+ // console.log(`publicKey: ${JSON.stringify(publicKey, null, 2)}`)
86
+
87
+ if (publicKey.includes('not found')) {
88
+ keysNotFound.push(thisAddr)
89
+ } else {
90
+ keys.push({
91
+ addr: thisAddr,
92
+ pubKey: publicKey,
93
+ nft: thisNft
94
+ })
95
+ }
96
+ }
97
+
98
+ return { keys, keysNotFound }
99
+ } catch (err) {
100
+ console.error('Error in findKeys()')
101
+ throw err
102
+ }
103
+ }
104
+ }
105
+
106
+ module.exports = NFTs