-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathScribe.sol
528 lines (433 loc) · 14.8 KB
/
Scribe.sol
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.16;
import {IChronicle} from "chronicle-std/IChronicle.sol";
import {Auth} from "chronicle-std/auth/Auth.sol";
import {Toll} from "chronicle-std/toll/Toll.sol";
import {IScribe} from "./IScribe.sol";
import {LibSchnorr} from "./libs/LibSchnorr.sol";
import {LibSecp256k1} from "./libs/LibSecp256k1.sol";
/**
* @title Scribe
* @custom:version 2.0.1
*
* @notice Efficient Schnorr multi-signature based Oracle
*
* @author Chronicle Labs, Inc
* @custom:security-contact [email protected]
*/
contract Scribe is IScribe, Auth, Toll {
using LibSchnorr for LibSecp256k1.Point;
using LibSecp256k1 for LibSecp256k1.Point;
using LibSecp256k1 for LibSecp256k1.JacobianPoint;
/// @inheritdoc IScribe
uint8 public constant decimals = 18;
/// @inheritdoc IScribe
bytes32 public constant feedRegistrationMessage = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256("Chronicle Feed Registration")
)
);
/// @inheritdoc IChronicle
bytes32 public immutable wat;
// -- Storage --
/// @dev Scribe's current value and corresponding age.
PokeData internal _pokeData;
/// @dev Statically allocated array of feeds' public keys.
/// Indexed via the public keys address' highest-order byte.
LibSecp256k1.Point[256] internal _pubKeys;
/// @inheritdoc IScribe
/// @dev Note to have as last in storage to enable downstream contracts to
/// pack the slot.
uint8 public bar;
// -- Constructor --
constructor(address initialAuthed, bytes32 wat_)
payable
Auth(initialAuthed)
{
require(wat_ != 0);
// Set wat immutable.
wat = wat_;
// Let initial bar be 2.
_setBar(2);
}
// -- Poke Functionality --
/// @dev Optimized function selector: 0x00000082.
/// Note that this function is _not_ defined via the IScribe interface
/// and one should _not_ depend on it.
function poke_optimized_7136211(
PokeData calldata pokeData,
SchnorrData calldata schnorrData
) external {
_poke(pokeData, schnorrData);
}
/// @inheritdoc IScribe
function poke(PokeData calldata pokeData, SchnorrData calldata schnorrData)
external
{
_poke(pokeData, schnorrData);
}
function _poke(PokeData calldata pokeData, SchnorrData calldata schnorrData)
internal
virtual
{
// Revert if pokeData stale.
if (pokeData.age <= _pokeData.age) {
revert StaleMessage(pokeData.age, _pokeData.age);
}
// Revert if pokeData from the future.
if (pokeData.age > uint32(block.timestamp)) {
revert FutureMessage(pokeData.age, uint32(block.timestamp));
}
// Revert if schnorrData does not prove integrity of pokeData.
bool ok;
bytes memory err;
// forgefmt: disable-next-item
(ok, err) = _verifySchnorrSignature(
constructPokeMessage(pokeData),
schnorrData
);
if (!ok) {
_revert(err);
}
// Store pokeData's val in _pokeData storage and set its age to now.
_pokeData.val = pokeData.val;
_pokeData.age = uint32(block.timestamp);
emit Poked(msg.sender, pokeData.val, pokeData.age);
}
/// @inheritdoc IScribe
function constructPokeMessage(PokeData memory pokeData)
public
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(wat, pokeData.val, pokeData.age))
)
);
}
// -- Schnorr Signature Verification --
/// @inheritdoc IScribe
function isAcceptableSchnorrSignatureNow(
bytes32 message,
SchnorrData calldata schnorrData
) external view returns (bool) {
bool ok;
(ok, /*err*/ ) = _verifySchnorrSignature(message, schnorrData);
return ok;
}
/// @custom:invariant Reverts iff out of gas.
/// @custom:invariant Runtime is O(bar).
function _verifySchnorrSignature(
bytes32 message,
SchnorrData calldata schnorrData
) internal view returns (bool, bytes memory) {
// Let feedPubKey be the currently processed feed's public key.
LibSecp256k1.Point memory feedPubKey;
// Let feedId be the currently processed feed's id.
uint8 feedId;
// Let aggPubKey be the sum of processed feeds' public keys.
// Note that Jacobian coordinates are used.
LibSecp256k1.JacobianPoint memory aggPubKey;
// Let bloom be a bloom filter to check for double signing attempts.
uint bloom;
// Fail if number feeds unequal to bar.
//
// Note that requiring equality constrains the verification's runtime
// from Ω(bar) to Θ(bar).
uint numberFeeds = schnorrData.feedIds.length;
if (numberFeeds != bar) {
return (false, _errorBarNotReached(uint8(numberFeeds), bar));
}
// Initiate feed variables with schnorrData's 0's feed index.
feedId = uint8(schnorrData.feedIds[0]);
feedPubKey = _pubKeys[feedId];
// Fail if feed not lifted.
if (feedPubKey.isZeroPoint()) {
return (false, _errorInvalidFeedId(feedId));
}
// Initiate bloom filter with feedId set.
bloom = 1 << feedId;
// Initiate aggPubKey with value of first feed's public key.
aggPubKey = feedPubKey.toJacobian();
for (uint8 i = 1; i < numberFeeds;) {
// Update feed variables.
feedId = uint8(schnorrData.feedIds[i]);
feedPubKey = _pubKeys[feedId];
// Fail if feed not lifted.
if (feedPubKey.isZeroPoint()) {
return (false, _errorInvalidFeedId(feedId));
}
// Fail if double signing attempted.
if (bloom & (1 << feedId) != 0) {
return (false, _errorDoubleSigningAttempted(feedId));
}
// Update bloom filter.
bloom |= 1 << feedId;
// assert(aggPubKey.x != feedPubKey.x); // Indicates rogue-key attack
// Add feedPubKey to already aggregated public keys.
aggPubKey.addAffinePoint(feedPubKey);
// forgefmt: disable-next-item
unchecked { ++i; }
}
// Fail if signature verification fails.
bool ok = aggPubKey.toAffine().verifySignature(
message, schnorrData.signature, schnorrData.commitment
);
if (!ok) {
return (false, _errorSchnorrSignatureInvalid());
}
// Otherwise Schnorr signature is valid.
return (true, new bytes(0));
}
// -- Toll'ed Read Functionality --
// - IChronicle Functions
/// @inheritdoc IChronicle
/// @dev Only callable by toll'ed address.
function read() external view virtual toll returns (uint) {
uint val = _pokeData.val;
require(val != 0);
return val;
}
/// @inheritdoc IChronicle
/// @dev Only callable by toll'ed address.
function tryRead() external view virtual toll returns (bool, uint) {
uint val = _pokeData.val;
return (val != 0, val);
}
/// @inheritdoc IChronicle
/// @dev Only callable by toll'ed address.
function readWithAge() external view virtual toll returns (uint, uint) {
uint val = _pokeData.val;
uint age = _pokeData.age;
require(val != 0);
return (val, age);
}
/// @inheritdoc IChronicle
/// @dev Only callable by toll'ed address.
function tryReadWithAge()
external
view
virtual
toll
returns (bool, uint, uint)
{
uint val = _pokeData.val;
uint age = _pokeData.age;
return val != 0 ? (true, val, age) : (false, 0, 0);
}
// - MakerDAO Compatibility
/// @inheritdoc IScribe
/// @dev Only callable by toll'ed address.
function peek() external view virtual toll returns (uint, bool) {
uint val = _pokeData.val;
return (val, val != 0);
}
/// @inheritdoc IScribe
/// @dev Only callable by toll'ed address.
function peep() external view virtual toll returns (uint, bool) {
uint val = _pokeData.val;
return (val, val != 0);
}
// - Chainlink Compatibility
/// @inheritdoc IScribe
/// @dev Only callable by toll'ed address.
function latestRoundData()
external
view
virtual
toll
returns (
uint80 roundId,
int answer,
uint startedAt,
uint updatedAt,
uint80 answeredInRound
)
{
roundId = 1;
answer = int(uint(_pokeData.val));
// assert(uint(answer) == uint(_pokeData.val));
startedAt = 0;
updatedAt = _pokeData.age;
answeredInRound = roundId;
}
/// @inheritdoc IScribe
/// @dev Only callable by toll'ed address.
function latestAnswer() external view virtual toll returns (int) {
uint val = _pokeData.val;
return int(val);
}
// -- Public Read Functionality --
/// @inheritdoc IScribe
function feeds(address who) external view returns (bool) {
uint8 feedId = uint8(uint(uint160(who)) >> 152);
LibSecp256k1.Point memory pubKey = _pubKeys[feedId];
return !pubKey.isZeroPoint() && pubKey.toAddress() == who;
}
/// @inheritdoc IScribe
function feeds(uint8 feedId) external view returns (bool, address) {
LibSecp256k1.Point memory pubKey = _pubKeys[feedId];
return pubKey.isZeroPoint()
? (false, address(0))
: (true, pubKey.toAddress());
}
/// @inheritdoc IScribe
function feeds() external view returns (address[] memory) {
address[] memory feeds_ = new address[](256);
LibSecp256k1.Point memory pubKey;
address feed;
uint ctr;
for (uint i; i < 256;) {
pubKey = _pubKeys[uint8(i)];
if (!pubKey.isZeroPoint()) {
feed = pubKey.toAddress();
feeds_[ctr] = feed;
// forgefmt: disable-next-item
unchecked { ++ctr; }
}
// forgefmt: disable-next-item
unchecked { ++i; }
}
assembly ("memory-safe") {
mstore(feeds_, ctr)
}
return feeds_;
}
// -- Auth'ed Functionality --
/// @inheritdoc IScribe
function lift(LibSecp256k1.Point memory pubKey, ECDSAData memory ecdsaData)
external
auth
returns (uint8)
{
return _lift(pubKey, ecdsaData);
}
/// @inheritdoc IScribe
function lift(
LibSecp256k1.Point[] memory pubKeys,
ECDSAData[] memory ecdsaDatas
) external auth returns (uint8[] memory) {
require(pubKeys.length == ecdsaDatas.length);
uint8[] memory feedIds = new uint8[](pubKeys.length);
for (uint i; i < pubKeys.length;) {
feedIds[i] = _lift(pubKeys[i], ecdsaDatas[i]);
// forgefmt: disable-next-item
unchecked { ++i; }
}
return feedIds;
}
function _lift(LibSecp256k1.Point memory pubKey, ECDSAData memory ecdsaData)
internal
returns (uint8)
{
address feed = pubKey.toAddress();
// assert(feed != address(0));
// forgefmt: disable-next-item
address recovered = ecrecover(
feedRegistrationMessage,
ecdsaData.v,
ecdsaData.r,
ecdsaData.s
);
require(feed == recovered);
uint8 feedId = uint8(uint(uint160(feed)) >> 152);
LibSecp256k1.Point memory sPubKey = _pubKeys[feedId];
if (sPubKey.isZeroPoint()) {
_pubKeys[feedId] = pubKey;
emit FeedLifted(msg.sender, feed);
} else {
// Note to be idempotent. However, disallow updating an id's feed
// via lifting without dropping the previous feed.
require(feed == sPubKey.toAddress());
}
return feedId;
}
/// @inheritdoc IScribe
function drop(uint8 feedId) external auth {
_drop(msg.sender, feedId);
}
/// @inheritdoc IScribe
function drop(uint8[] memory feedIds) external auth {
for (uint i; i < feedIds.length;) {
_drop(msg.sender, feedIds[i]);
// forgefmt: disable-next-item
unchecked { ++i; }
}
}
function _drop(address caller, uint8 feedId) internal virtual {
LibSecp256k1.Point memory pubKey = _pubKeys[feedId];
if (!pubKey.isZeroPoint()) {
delete _pubKeys[feedId];
emit FeedDropped(caller, pubKey.toAddress());
}
}
/// @inheritdoc IScribe
function setBar(uint8 bar_) external auth {
_setBar(bar_);
}
function _setBar(uint8 bar_) internal virtual {
require(bar_ != 0);
if (bar != bar_) {
emit BarUpdated(msg.sender, bar, bar_);
bar = bar_;
}
}
// -- Internal Helpers --
function _revert(bytes memory err) internal pure {
// assert(err.length != 0);
assembly ("memory-safe") {
let size := mload(err)
let offset := add(err, 0x20)
revert(offset, size)
}
}
function _errorBarNotReached(uint8 got, uint8 want)
internal
pure
returns (bytes memory)
{
// assert(got != want);
return abi.encodeWithSelector(IScribe.BarNotReached.selector, got, want);
}
function _errorInvalidFeedId(uint8 feedId)
internal
pure
returns (bytes memory)
{
// assert(_pubKeys[feedId].isZeroPoint());
return abi.encodeWithSelector(IScribe.InvalidFeedId.selector, feedId);
}
function _errorDoubleSigningAttempted(uint8 feedId)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
IScribe.DoubleSigningAttempted.selector, feedId
);
}
function _errorSchnorrSignatureInvalid()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(IScribe.SchnorrSignatureInvalid.selector);
}
// -- Overridden Toll Functions --
/// @dev Defines authorization for IToll's authenticated functions.
function toll_auth() internal override(Toll) auth {}
}
/**
* @dev Contract overwrite to deploy contract instances with specific naming.
*
* For more info, see docs/Deployment.md.
*/
contract Chronicle_BASE_QUOTE_COUNTER is Scribe {
// @todo ^^^^ ^^^^^ ^^^^^^^ Adjust name of Scribe instance.
constructor(address initialAuthed, bytes32 wat_)
Scribe(initialAuthed, wat_)
{}
}