-
Notifications
You must be signed in to change notification settings - Fork 44
/
lib.rs
562 lines (472 loc) · 16.9 KB
/
lib.rs
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use anchor_lang::prelude::*;
use access_controller::AccessController;
mod state;
use crate::state::with_store;
pub use crate::state::{NewTransmission, Store as State, Transmission, Transmissions};
declare_id!("HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny");
static THRESHOLD_MULTIPLIER: u128 = 100000;
const FEED_VERSION: u8 = 2;
#[derive(Clone)]
pub struct Store;
impl anchor_lang::Id for Store {
fn id() -> Pubkey {
ID
}
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub enum Scope {
Version,
Decimals,
Description,
RoundData { round_id: u32 },
LatestRoundData,
Aggregator,
// ProposedAggregator
// Owner
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct Round {
pub round_id: u32,
pub slot: u64,
pub timestamp: u32,
pub answer: i128,
}
#[program]
pub mod store {
use super::*;
// Feed methods
pub fn create_feed(
ctx: Context<CreateFeed>,
description: String,
decimals: u8,
granularity: u8,
live_length: u32,
) -> Result<()> {
use std::mem::size_of;
let feed = &mut ctx.accounts.feed;
// Validate the feed account is of the correct size
let len = feed.to_account_info().data_len();
// discriminator + header size
let len = len
.checked_sub(8 + state::HEADER_SIZE)
.ok_or(ErrorCode::InsufficientSize)?;
require!(
len % size_of::<Transmission>() == 0,
ErrorCode::InsufficientSize
);
let space = len / size_of::<Transmission>();
// Live length must not exceed total capacity
require!(live_length <= space as u32, ErrorCode::InvalidInput);
// Both inputs should also be more than zero
require!(live_length > 0, ErrorCode::InvalidInput);
require!(granularity > 0, ErrorCode::InvalidInput);
feed.version = FEED_VERSION;
feed.state = Transmissions::NORMAL;
feed.owner = ctx.accounts.authority.key();
feed.granularity = granularity;
feed.live_length = live_length;
feed.writer = Pubkey::default();
feed.decimals = decimals;
let description = description.as_bytes();
require!(description.len() <= 32, ErrorCode::InvalidInput);
feed.description[..description.len()].copy_from_slice(description);
Ok(())
}
#[access_control(owner(&ctx.accounts.owner, &ctx.accounts.authority))]
pub fn close_feed(ctx: Context<CloseFeed>) -> Result<()> {
// NOTE: Close is handled by anchor on exit due to the `close` attribute
Ok(())
}
#[access_control(owner(&ctx.accounts.owner, &ctx.accounts.authority))]
pub fn transfer_feed_ownership(
ctx: Context<TransferFeedOwnership>,
proposed_owner: Pubkey,
) -> Result<()> {
ctx.accounts.feed.proposed_owner = proposed_owner;
Ok(())
}
pub fn accept_feed_ownership(ctx: Context<AcceptFeedOwnership>) -> Result<()> {
let store: std::result::Result<AccountLoader<State>, _> =
try_from!(AccountLoader<State>, &ctx.accounts.proposed_owner);
let proposed_owner = match store {
// if the feed is owned by a store, validate the store's owner signed
Ok(store) => store.load()?.owner,
// else, it's an individual owner
Err(_err) => ctx.accounts.proposed_owner.key(),
};
require!(
ctx.accounts.authority.key == &proposed_owner,
ErrorCode::Unauthorized
);
let feed = &mut ctx.accounts.feed;
feed.owner = std::mem::take(&mut feed.proposed_owner);
Ok(())
}
#[access_control(owner(&ctx.accounts.owner, &ctx.accounts.authority))]
pub fn set_validator_config(
ctx: Context<SetFeedConfig>,
flagging_threshold: u32,
) -> Result<()> {
ctx.accounts.feed.flagging_threshold = flagging_threshold;
Ok(())
}
#[access_control(owner(&ctx.accounts.owner, &ctx.accounts.authority))]
pub fn set_writer(ctx: Context<SetFeedConfig>, writer: Pubkey) -> Result<()> {
ctx.accounts.feed.writer = writer;
Ok(())
}
// NOTE: to bulk lower, a batch transaction can be sent with a bunch of lower calls
#[access_control(has_lowering_access(
&ctx.accounts.owner,
&ctx.accounts.access_controller,
&ctx.accounts.authority,
))]
pub fn lower_flag(ctx: Context<LowerFlag>) -> Result<()> {
ctx.accounts.feed.state = Transmissions::NORMAL;
Ok(())
}
pub fn submit(ctx: Context<Submit>, round: NewTransmission) -> Result<()> {
let clock = Clock::get()?;
let round = Transmission {
slot: clock.slot,
answer: round.answer,
timestamp: round.timestamp as u32,
..Default::default()
};
let previous_round = with_store(&mut ctx.accounts.feed, |store| {
let previous = store.latest();
store.insert(round);
previous
})?;
let flagging_threshold = ctx.accounts.feed.flagging_threshold;
let is_valid = if let Some(previous_round) = previous_round {
is_valid(flagging_threshold, previous_round.answer, round.answer)
} else {
true
};
if !is_valid {
// raise flag
ctx.accounts.feed.state = Transmissions::FLAGGED;
}
Ok(())
}
// Store methods
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let mut store = ctx.accounts.store.load_init()?;
store.owner = ctx.accounts.owner.key();
store.lowering_access_controller = ctx.accounts.lowering_access_controller.key();
Ok(())
}
pub fn transfer_store_ownership(
ctx: Context<TransferStoreOwnership>,
proposed_owner: Pubkey,
) -> Result<()> {
let store = &mut *ctx.accounts.store.load_mut()?;
store.proposed_owner = proposed_owner;
Ok(())
}
pub fn accept_store_ownership(ctx: Context<AcceptStoreOwnership>) -> Result<()> {
let store = &mut *ctx.accounts.store.load_mut()?;
store.owner = std::mem::take(&mut store.proposed_owner);
Ok(())
}
pub fn set_lowering_access_controller(ctx: Context<SetAccessController>) -> Result<()> {
let mut store = ctx.accounts.store.load_mut()?;
store.lowering_access_controller = ctx.accounts.access_controller.key();
Ok(())
}
/// The query instruction takes a `Query` and serializes the response in a fixed format. That way queries
/// are not bound to the underlying layout.
pub fn query(ctx: Context<Query>, scope: Scope) -> Result<()> {
use std::io::Cursor;
let mut buf = Cursor::new(Vec::with_capacity(128)); // TODO: calculate max size
let header = &ctx.accounts.feed;
match scope {
Scope::Version => {
let data = header.version;
data.serialize(&mut buf)?;
}
Scope::Decimals => {
let data = header.decimals;
data.serialize(&mut buf)?;
}
Scope::Description => {
// Look for the first null byte
let end = header
.description
.iter()
.position(|byte| byte == &0)
.unwrap_or(header.description.len());
let description = String::from_utf8(header.description[..end].to_vec())
.map_err(|_err| ErrorCode::InvalidInput)?;
let data = description;
data.serialize(&mut buf)?;
}
Scope::RoundData { round_id } => {
let round = with_store(&mut ctx.accounts.feed, |store| store.fetch(round_id))?
.ok_or(ErrorCode::NotFound)?;
let data = Round {
round_id,
slot: round.slot,
answer: round.answer,
timestamp: round.timestamp,
};
data.serialize(&mut buf)?;
}
Scope::LatestRoundData => {
let round = with_store(&mut ctx.accounts.feed, |store| store.latest())?
.ok_or(ErrorCode::NotFound)?;
let header = &ctx.accounts.feed;
let data = Round {
round_id: header.latest_round_id,
slot: round.slot,
answer: round.answer,
timestamp: round.timestamp,
};
data.serialize(&mut buf)?;
}
Scope::Aggregator => {
let data = header.writer;
data.serialize(&mut buf)?;
}
}
anchor_lang::solana_program::program::set_return_data(buf.get_ref());
Ok(())
}
}
fn is_valid(flagging_threshold: u32, previous_answer: i128, answer: i128) -> bool {
if previous_answer == 0i128 {
return true;
}
// https://github.com/rust-lang/rust/issues/89492
fn abs_diff(slf: i128, other: i128) -> u128 {
if slf < other {
(other as u128).wrapping_sub(slf as u128)
} else {
(slf as u128).wrapping_sub(other as u128)
}
}
let change = abs_diff(previous_answer, answer);
let ratio_numerator = match change.checked_mul(THRESHOLD_MULTIPLIER) {
Some(ratio_numerator) => ratio_numerator,
None => return false,
};
let ratio = ratio_numerator / previous_answer.unsigned_abs();
ratio <= u128::from(flagging_threshold)
}
// https://github.com/coral-xyz/anchor/pull/2770
#[macro_export]
macro_rules! try_from {
($ty: ty, $acc: expr) => {
<$ty>::try_from(unsafe { core::mem::transmute::<_, &AccountInfo<'_>>($acc.as_ref()) })
};
}
// Only owner access
fn owner<'info>(owner: &UncheckedAccount<'info>, authority: &Signer) -> Result<()> {
let store: std::result::Result<AccountLoader<'info, State>, _> =
try_from!(AccountLoader<'info, State>, owner);
let owner = match store {
// if the feed is owned by a store, validate the store's owner signed
Ok(store) => store.load()?.owner,
// else, it's an individual owner
Err(_err) => *owner.key,
};
require!(authority.key == &owner, ErrorCode::Unauthorized);
Ok(())
}
fn has_lowering_access(
owner: &UncheckedAccount,
controller: &UncheckedAccount,
authority: &Signer,
) -> Result<()> {
let store: std::result::Result<AccountLoader<State>, _> =
try_from!(AccountLoader<State>, owner);
match store {
// if the feed is owned by a store
Ok(store) => {
let store = store.load()?;
let is_owner = store.owner == authority.key();
// the signer is the store owner, fast path return
if is_owner {
return Ok(());
}
// else, we check the lowering_access_controller
// The controller account has to match the lowering_access_controller on the store
require!(
controller.key() == store.lowering_access_controller,
ErrorCode::InvalidInput
);
let controller = try_from!(AccountLoader<AccessController>, controller)?;
// Check if the key is present on the access controller
let has_access = access_controller::has_access(&controller, authority.key)
// TODO: better mapping, maybe InvalidInput?
.map_err(|_| ErrorCode::Unauthorized)?;
require!(has_access, ErrorCode::Unauthorized);
}
// else, it's an individual owner
Err(_err) => {
require!(authority.key == owner.key, ErrorCode::Unauthorized);
}
};
Ok(())
}
#[cfg(feature = "cpi")]
pub mod accessors {
use crate::cpi::{self, accounts::Query};
use crate::{Round, Scope};
use anchor_lang::prelude::*;
use anchor_lang::solana_program;
fn query<'info, T: AnchorDeserialize>(
program_id: AccountInfo<'info>,
feed: AccountInfo<'info>,
scope: Scope,
) -> Result<T> {
let cpi = CpiContext::new(program_id, Query { feed });
cpi::query(cpi, scope)?;
let (_key, data) = solana_program::program::get_return_data().unwrap();
let data = T::try_from_slice(&data)?;
Ok(data)
}
pub fn version<'info>(program_id: AccountInfo<'info>, feed: AccountInfo<'info>) -> Result<u8> {
query(program_id, feed, Scope::Version)
}
pub fn decimals<'info>(program_id: AccountInfo<'info>, feed: AccountInfo<'info>) -> Result<u8> {
query(program_id, feed, Scope::Decimals)
}
pub fn description<'info>(
program_id: AccountInfo<'info>,
feed: AccountInfo<'info>,
) -> Result<String> {
query(program_id, feed, Scope::Description)
}
pub fn round_data<'info>(
program_id: AccountInfo<'info>,
feed: AccountInfo<'info>,
round_id: u32,
) -> Result<Round> {
query(program_id, feed, Scope::RoundData { round_id })
}
pub fn latest_round_data<'info>(
program_id: AccountInfo<'info>,
feed: AccountInfo<'info>,
) -> Result<Round> {
query(program_id, feed, Scope::LatestRoundData)
}
pub fn aggregator<'info>(
program_id: AccountInfo<'info>,
feed: AccountInfo<'info>,
) -> Result<Pubkey> {
query(program_id, feed, Scope::Aggregator)
}
}
#[error_code]
pub enum ErrorCode {
#[msg("Unauthorized")]
Unauthorized = 0,
#[msg("Invalid input")]
InvalidInput = 1,
NotFound = 2,
#[msg("Invalid version")]
InvalidVersion = 3,
#[msg("Insufficient or invalid feed account size, has to be `8 + HEADER_SIZE + n * size_of::<Transmission>()`")]
InsufficientSize = 4,
}
// Feed methods
#[derive(Accounts)]
pub struct CreateFeed<'info> {
#[account(zero)]
pub feed: Account<'info, Transmissions>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct CloseFeed<'info> {
#[account(mut, close = receiver)]
pub feed: Account<'info, Transmissions>,
/// CHECK: through the owner() access_control
#[account(address = feed.owner)]
pub owner: UncheckedAccount<'info>,
#[account(mut)]
pub receiver: SystemAccount<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct SetFeedConfig<'info> {
#[account(mut)]
pub feed: Account<'info, Transmissions>,
/// CHECK: through the owner() access_control
#[account(address = feed.owner)]
pub owner: UncheckedAccount<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct LowerFlag<'info> {
#[account(mut)]
pub feed: Account<'info, Transmissions>,
/// CHECK: through the has_lowering_access() access_control
#[account(address = feed.owner)]
pub owner: UncheckedAccount<'info>,
pub authority: Signer<'info>,
/// CHECK: through the has_lowering_access() access_control
pub access_controller: UncheckedAccount<'info>,
}
#[derive(Accounts)]
pub struct TransferFeedOwnership<'info> {
#[account(mut)]
pub feed: Account<'info, Transmissions>,
/// CHECK: through the owner() access_control
#[account(address = feed.owner)]
pub owner: UncheckedAccount<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct AcceptFeedOwnership<'info> {
#[account(mut)]
pub feed: Account<'info, Transmissions>,
/// CHECK: we validate this inside accept_feed_ownership
#[account(address = feed.proposed_owner)]
pub proposed_owner: UncheckedAccount<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct Submit<'info> {
/// The OCR2 feed
#[account(mut)]
pub feed: Account<'info, Transmissions>,
// check if this particular ocr2 cluster is allowed to write to the feed
#[account(address = feed.writer @ ErrorCode::Unauthorized)]
pub authority: Signer<'info>,
}
// Store methods
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(zero)]
pub store: AccountLoader<'info, State>,
pub owner: Signer<'info>,
pub lowering_access_controller: AccountLoader<'info, AccessController>,
}
#[derive(Accounts)]
pub struct TransferStoreOwnership<'info> {
#[account(mut)]
pub store: AccountLoader<'info, State>,
#[account(address = store.load()?.owner @ ErrorCode::Unauthorized)]
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct AcceptStoreOwnership<'info> {
#[account(mut)]
pub store: AccountLoader<'info, State>,
#[account(address = store.load()?.proposed_owner @ ErrorCode::Unauthorized)]
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct SetAccessController<'info> {
#[account(mut)]
pub store: AccountLoader<'info, State>,
#[account(address = store.load()?.owner @ ErrorCode::Unauthorized)]
pub authority: Signer<'info>,
pub access_controller: AccountLoader<'info, AccessController>,
}
#[derive(Accounts)]
pub struct Query<'info> {
pub feed: Account<'info, Transmissions>,
}