proof.ts 8.33 KB
Newer Older
1
2
3
4
5
import {LOCAL_RULES_HELPERS} from "../../../lib/rules/local_rules"
import {hashf} from "../../../lib/common"
import {DBBlock} from "../../../lib/db/DBBlock"
import {ConfDTO} from "../../../lib/dto/ConfDTO"
import {Constants} from "./constants"
6
import {KeyGen} from "../../../lib/common/crypto/keyring"
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

const moment = require('moment');
const dos2unix = require('duniter-common').dos2unix;
const querablep = require('querablep');
const rawer = require('duniter-common').rawer;

const PAUSES_PER_TURN = 5;

// This value can be changed
let TURN_DURATION_IN_MILLISEC = 100;

let computing = querablep(Promise.resolve(null));
let askedStop = false;

// By default, we do not prefix the PoW by any number
let prefix = 0;

let signatureFunc:any, lastSecret:any, currentCPU = 1;

process.on('uncaughtException', (err:any) => {
  console.error(err.stack || Error(err))
  if (process.send) {
    process.send({error: err});
  } else {
    throw Error('process.send() is not defined')
  }
});

process.on('message', async (message) => {

  switch (message.command) {

    case 'newPoW':
      (async () => {
        askedStop = true

        // Very important: do not await if the computation is already done, to keep the lock on JS engine
        if (!computing.isFulfilled()) {
          await computing;
        }

        const res = await beginNewProofOfWork(message.value);
        answer(message, res);
      })()
      break;

    case 'cancel':
      if (!computing.isFulfilled()) {
        askedStop = true;
      }
      break;

    case 'conf':
      if (message.value.cpu !== undefined) {
        currentCPU = message.value.cpu
      }
      if (message.value.prefix !== undefined) {
        prefix = message.value.prefix
      }
      answer(message, { currentCPU, prefix });
      break;
  }

})

function beginNewProofOfWork(stuff:any) {
  askedStop = false;
  computing = querablep((async () => {

    /*****************
     * PREPARE POW STUFF
     ****************/

    let nonce = 0;
    const conf = stuff.conf;
    const block = stuff.block;
    const nonceBeginning = stuff.nonceBeginning;
    const nbZeros = stuff.zeros;
    const pair = stuff.pair;
    const forcedTime = stuff.forcedTime;
    currentCPU = conf.cpu || Constants.DEFAULT_CPU;
    prefix = parseInt(conf.prefix || prefix) * 10 * Constants.NONCE_RANGE
    const highMark = stuff.highMark;
    const turnDuration = stuff.turnDuration || TURN_DURATION_IN_MILLISEC
    let sigFunc = null;
    if (signatureFunc && lastSecret === pair.sec) {
      sigFunc = signatureFunc;
    }
    else {
      lastSecret = pair.sec;
97
      sigFunc = (msg:string) => KeyGen(pair.pub, pair.sec).signSync(msg)
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
    }
    signatureFunc = sigFunc;
    let pow = "", sig = "", raw = "";

    /*****************
     * GO!
     ****************/

    let testsCount = 0;
    let found = false;
    let score = 0;
    let turn = 0;

    while (!found && !askedStop) {

      /*****************
       * A TURN
       ****************/

      await Promise.race([

        // I. Stop the turn if it exceeds `turnDuration` ms
        countDown(turnDuration),

        // II. Process the turn's PoW
        (async () => {

          /*****************
           * A TURN OF POW ~= 100ms by default
           * --------------------
           *
           * The concept of "turn" is required to limit the CPU usage.
           * We need a time reference to have the speed = nb tests / period of time.
           * Here we have:
           *
           *   - speed = testsCount / turn
           *
           * We have taken 1 turn = 100ms to control the CPU usage after 100ms of PoW. This means that during the
           * very first 100ms of the PoW, CPU usage = 100%. Then it becomes controlled to the %CPU set.
           ****************/

            // Prove
          let i = 0;
          const thisTurn = turn;
          const pausePeriod = score ? score / PAUSES_PER_TURN : 10; // number of pauses per turn
          // We limit the number of tests according to CPU usage
          const testsPerRound = score ? Math.floor(score * currentCPU) : 1000 * 1000 * 1000

          // Time is updated regularly during the proof
          block.time = getBlockTime(block, conf, forcedTime)
          if (block.number === 0) {
            block.medianTime = block.time
          }
          block.inner_hash = getBlockInnerHash(block);

          /*****************
           * Iterations of a turn
           ****************/

          while(!found && i < testsPerRound && thisTurn === turn && !askedStop) {

            // Nonce change (what makes the PoW change if the time field remains the same)
            nonce++

            /*****************
             * A PROOF OF WORK
             ****************/

            // The final nonce is composed of 3 parts
            block.nonce = prefix + nonceBeginning + nonce
            raw = dos2unix("InnerHash: " + block.inner_hash + "\nNonce: " + block.nonce + "\n")
            sig = dos2unix(sigFunc(raw))
            pow = hashf("InnerHash: " + block.inner_hash + "\nNonce: " + block.nonce + "\n" + sig + "\n").toUpperCase()

            /*****************
             * Check the POW result
             ****************/

            let j = 0, charOK = true;
            while (j < nbZeros && charOK) {
              charOK = pow[j] === '0';
              j++;
            }
            if (charOK) {
              found = !!(pow[nbZeros].match(new RegExp('[0-' + highMark + ']')))
            }
            if (!found && nbZeros > 0 && j - 1 >= Constants.POW_MINIMAL_TO_SHOW) {
              pSend({ pow: { pow: pow, block: block, nbZeros: nbZeros }});
            }

            /*****************
             * - Update local vars
             * - Allow to receive stop signal
             ****************/

            if (!found && !askedStop) {
              i++;
              testsCount++;
              if (i % pausePeriod === 0) {
                await countDown(0); // Very low pause, just the time to process eventual end of the turn
              }
            }
          }

          /*****************
           * Check the POW result
           ****************/
          if (!found) {

            // CPU speed recording
            if (turn > 0 && !score) {
              score = testsCount;
            }

            /*****************
             * UNLOAD CPU CHARGE
             ****************/
            // We wait for a maximum time of `turnDuration`.
            // This will trigger the end of the turn by the concurrent race I. During that time, the proof.js script
            // just does nothing: this gives of a bit of breath to the CPU. Tthe amount of "breath" depends on the "cpu"
            // parameter.
            await countDown(turnDuration);
          }
        })()
      ]);

      // Next turn
      turn++
    }

    /*****************
     * POW IS OVER
     * -----------
     *
     * We either have found a valid POW or a stop event has been detected.
     ****************/

    if (askedStop) {

      // PoW stopped
      askedStop = false;
      return null

    } else {

      // PoW success
      block.hash = pow
      block.signature = sig
      return {
        pow: {
          block: block,
          testsCount: testsCount,
          pow: pow
        }
      }
    }
  })())

  return computing;
}

function countDown(duration:number) {
  return new Promise((resolve) => setTimeout(resolve, duration));
}

function getBlockInnerHash(block:DBBlock) {
  const raw = rawer.getBlockInnerPart(block);
  return hashf(raw)
}

function getBlockTime (block:DBBlock, conf:ConfDTO, forcedTime:number|null) {
  if (forcedTime) {
    return forcedTime;
  }
  const now = moment.utc().unix();
  const maxAcceleration = LOCAL_RULES_HELPERS.maxAcceleration(conf);
  const timeoffset = block.number >= conf.medianTimeBlocks ? 0 : conf.rootoffset || 0;
  const medianTime = block.medianTime;
  const upperBound = block.number === 0 ? medianTime : Math.min(medianTime + maxAcceleration, now - timeoffset);
  return Math.max(medianTime, upperBound);
}

function answer(message:any, theAnswer:any) {
  return pSend({
    uuid: message.uuid,
    answer: theAnswer
  })
}

function pSend(stuff:any) {
  return new Promise(function (resolve, reject) {
    if (process.send) {
      process.send(stuff, function (error:any) {
        !error && resolve();
        error && reject();
      })
    } else {
      reject('process.send() is not defined')
    }
  });
}