-
Notifications
You must be signed in to change notification settings - Fork 106
/
URSMRegistrationManager.js
270 lines (240 loc) · 8.5 KB
/
URSMRegistrationManager.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
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
const axios = require('axios')
const _ = require('lodash')
const { libs } = require('@audius/sdk')
const LibsUtils = libs.Utils
const { logger } = require('../logging')
const { generateTimestampAndSignature } = require('../apiSigning')
const { parseCNodeResponse } = require('../apiHelpers')
const NumSignaturesRequired = 3
/**
* Allow for several seconds for the request for signature response, as
* the route makes multiple web requests internally
*/
const RequestForSignatureTimeoutMs = 30000 /** 30sec */
/**
* This Service is responsible for registering this node on the UserReplicaSetManager L2 contract (URSM)
*
* @notice Service is backwards compatible, and will work before and after URSM contract deployment
*/
class URSMRegistrationManager {
constructor(nodeConfig, audiusLibs) {
this.nodeConfig = nodeConfig
this.audiusLibs = audiusLibs
this.delegateOwnerWallet = nodeConfig.get('delegateOwnerWallet')
this.delegatePrivateKey = nodeConfig.get('delegatePrivateKey')
this.spOwnerWallet = nodeConfig.get('spOwnerWallet')
this.oldDelegateOwnerWallet = this.nodeConfig.get('oldDelegateOwnerWallet')
this.oldDelegatePrivateKey = this.nodeConfig.get('oldDelegatePrivateKey')
this.entityManagerReplicaSetEnabled = this.nodeConfig.get(
'entityManagerReplicaSetEnabled'
)
if (
!this.audiusLibs ||
!this.delegateOwnerWallet ||
!this.delegatePrivateKey ||
!this.spOwnerWallet
) {
throw new Error(
'URSMRegistrationManager cannot start due to missing required configs'
)
}
}
logInfo(msg) {
logger.info(`URSMRegistrationManager || ${msg}`)
}
logError(msg) {
logger.error(`URSMRegistrationManager ERROR || ${msg}`)
}
/**
* Registers node on UserReplicaSetManager contract (URSM)
*
* Steps:
* 1. Fetch node record from L1 ServiceProviderFactory for spID
* a. Short-circuit if no L1 record found
* 2. Fetch node record from L2 UserReplicaSetManager for spID
* a. Short-circuit if L2 record for node already matches L1 record (i.e. delegateOwnerWallets match)
* 3. Fetch list of all nodes registered on URSM, in order to submit requests for proposal
* a. Randomize list to minimize bias + de-dupe by ownerWallet to meet on-chain uniqueness constraint
* 4. Request signatures from all registered nodes, in batches of 3, until 3 successful signatures received
* a. Error if all available nodes contacted without 3 successful signatures
* 5. Submit registration transaction to URSM with signatures
*/
async run() {
this.logInfo('Beginning URSM registration process')
/**
* (Backwards-compatibility) Short circuit if L2 URSM contract not yet deployed
*/
if (!this.audiusLibs.contracts.UserReplicaSetManagerClient) {
throw new Error(
'URSMRegistration cannot run until UserReplicaSetManager contract is deployed'
)
}
const spID = this.nodeConfig.get('spID')
if (!spID) {
throw new Error('URSMRegistration cannot run without spID config')
}
/**
* 1. Fetch node record from L1 ServiceProviderFactory for spID
*/
const spRecordFromSPFactory =
await this.audiusLibs.ethContracts.ServiceProviderFactoryClient.getServiceEndpointInfo(
'content-node',
spID
)
let {
owner: ownerWalletFromSPFactory,
delegateOwnerWallet: delegateOwnerWalletFromSPFactory,
endpoint: endpointFromSPFactory
} = spRecordFromSPFactory
delegateOwnerWalletFromSPFactory =
delegateOwnerWalletFromSPFactory.toLowerCase()
/**
* 1-a. Short-circuit if no L1 record found
*/
if (
LibsUtils.isZeroAddress(ownerWalletFromSPFactory) ||
LibsUtils.isZeroAddress(delegateOwnerWalletFromSPFactory) ||
!endpointFromSPFactory
) {
throw new Error('Failed to find valid L1 record for node')
}
/**
* 2. Fetch node record from L2 UserReplicaSetManager for spID
*/
const delegateOwnerWalletFromURSM = (
await this.audiusLibs.contracts.UserReplicaSetManagerClient.getContentNodeWallets(
spID
)
).delegateOwnerWallet.toLowerCase()
/**
* 2-a. Short-circuit if L2 record for node already matches L1 record (i.e. delegateOwnerWallets match)
*/
const activeDelegateOwnerWallet =
this.oldDelegateOwnerWallet || this.delegateOwnerWallet
this.logError(
`activeDelegateOwnerWallet: ${activeDelegateOwnerWallet.toLowerCase()} // delegateOwnerWalletFromURSM: ${delegateOwnerWalletFromURSM}`
)
if (
!this.entityManagerReplicaSetEnabled &&
activeDelegateOwnerWallet.toLowerCase() === delegateOwnerWalletFromURSM
) {
// Update config
this.nodeConfig.set('isRegisteredOnURSM', true)
this.logInfo(
`Node already registered on URSM with same delegateOwnerWallet`
)
return
}
if (this.oldDelegateOwnerWallet) {
// New node registration is disabled if using oldDelegateOwnerWallet and above URSM check failed
throw new Error('Something went wrong if we got here')
}
/**
* 3. Fetch list of all nodes registered on URSM, in order to submit requests for proposal
* a. Randomize list to minimize bias
* b. Remove duplicates by owner_wallet key due to on-chain uniqueness constraint
*/
let URSMContentNodes =
await this.audiusLibs.discoveryProvider.getURSMContentNodes()
URSMContentNodes = URSMContentNodes.filter((node) => node.endpoint)
URSMContentNodes = _.shuffle(URSMContentNodes)
URSMContentNodes = Object.values(_.keyBy(URSMContentNodes, 'owner_wallet'))
/**
* 4. Request signatures from all registered nodes, in batches of 3, until 3 successful signatures received
*/
let receivedSignatures = []
for (let i = 0; i < URSMContentNodes.length; i += NumSignaturesRequired) {
if (receivedSignatures.length >= 3) {
break
}
const nodesToAttempt = URSMContentNodes.slice(i, NumSignaturesRequired)
let responses = await Promise.all(
nodesToAttempt.map(async (node) => {
try {
const resp = await this._submitRequestForSignature(
node.endpoint,
spID
)
this.logInfo(
`Successfully received signature from ${node.endpoint}`
)
return resp
} catch (e) {
this.logError(
`Failed to receive signature from ${node.endpoint} with error ${e}`
)
return null
}
})
)
responses = responses.filter(Boolean)
receivedSignatures = receivedSignatures.concat(responses)
}
/**
* 4-a. Error if all available nodes contacted without 3 successful signatures
*/
if (receivedSignatures.length < 3) {
throw new Error(
'Failed to receive 3 signatures after requesting from all available nodes'
)
}
/**
* 5. Submit registration transaction to URSM with signatures
*/
const proposerSpIDs = receivedSignatures.map(
(signatureObj) => signatureObj.spID
)
const proposerNonces = receivedSignatures.map(
(signatureObj) => signatureObj.nonce
)
try {
// internally this call will retry
await this.audiusLibs.contracts.UserReplicaSetManagerClient.addOrUpdateContentNode(
spID,
[this.delegateOwnerWallet, this.spOwnerWallet],
proposerSpIDs,
proposerNonces,
receivedSignatures[0].sig,
receivedSignatures[1].sig,
receivedSignatures[2].sig
)
// Update config
this.nodeConfig.set('isRegisteredOnURSM', true)
this.logInfo('Successfully registered self on URSM')
} catch (e) {
throw new Error(`URSMRegistration contract call failed ${e}`)
}
}
/**
* Given endpoint of a content node, submits request for signature
* @param {string} nodeEndpoint
*/
async _submitRequestForSignature(nodeEndpoint, spID) {
const { timestamp, signature } = generateTimestampAndSignature(
{ spID },
this.delegatePrivateKey
)
const RFPResp = await axios({
baseURL: nodeEndpoint,
url: '/ursm_request_for_signature',
method: 'get',
timeout: RequestForSignatureTimeoutMs,
params: {
spID,
timestamp,
signature
}
})
const { responseData } = parseCNodeResponse(RFPResp, [
'spID',
'nonce',
'sig'
])
return {
spID: responseData.spID,
nonce: responseData.nonce,
sig: responseData.sig
}
}
}
module.exports = URSMRegistrationManager