This repository has been archived by the owner on Feb 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlib.rs
executable file
·359 lines (315 loc) · 13.2 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
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(trace_macros)]
use pink_extension as pink;
// Define a trait for cross-contract call. Necessary to enable it in unit tests.
pub mod issuable {
use ink_env::AccountId;
use ink_lang as ink;
trace_macros!(true);
#[openbrush::trait_definition(mock = fat_badges::FatBadges)]
pub trait Issuable {
#[ink(message)]
fn issue(&mut self, id: u32, dest: AccountId) -> fat_badges::Result<()>;
}
trace_macros!(false);
#[openbrush::wrapper]
pub type IssuableRef = dyn Issuable;
}
#[pink::contract(env=PinkEnvironment)]
mod easy_oracle {
use crate::issuable::IssuableRef;
use crate::pink::{http_get, PinkEnvironment};
use fat_utils::attestation;
use ink_prelude::{
string::{String, ToString},
vec::Vec,
};
use ink_storage::traits::SpreadAllocate;
use ink_storage::Mapping;
use scale::{Decode, Encode};
#[ink(storage)]
#[derive(SpreadAllocate)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct EasyOracle {
admin: AccountId,
badge_contract_options: Option<(AccountId, u32)>,
attestation_verifier: attestation::Verifier,
attestation_generator: attestation::Generator,
linked_users: Mapping<String, ()>,
}
/// Errors that can occur upon calling this contract.
#[derive(Debug, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
BadOrigin,
BadgeContractNotSetUp,
InvalidUrl,
RequestFailed,
NoClaimFound,
InvalidAddressLength,
InvalidAddress,
NoPermission,
InvalidSignature,
UsernameAlreadyInUse,
AccountAlreadyInUse,
FailedToIssueBadge,
}
/// Type alias for the contract's result type.
pub type Result<T> = core::result::Result<T, Error>;
impl EasyOracle {
#[ink(constructor)]
pub fn new() -> Self {
// Create the attestation helpers
let (generator, verifier) = attestation::create(b"gist-attestation-key");
// Save sender as the contract admin
let admin = Self::env().caller();
ink_lang::utils::initialize_contract(|this: &mut Self| {
this.admin = admin;
this.badge_contract_options = None;
this.attestation_generator = generator;
this.attestation_verifier = verifier;
})
}
// Commands
/// Sets the downstream badge contract
///
/// Only the admin can call it.
pub fn config_issuer(&mut self, contract: AccountId, badge_id: u32) -> Result<()> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::BadOrigin);
}
// Create a reference to the already deployed FatBadges contract
self.badge_contract_options = Some((contract, badge_id));
Ok(())
}
/// Redeems a POAP with a signed `attestation`. (callable)
///
/// The attestation must be created by [`attest_gist`] function. After the verification of
/// the attestation, the the sender account will the linked to a Github username. Then a
/// POAP redemption code will be allocated to the sender.
///
/// Each blockchain account and github account can only be linked once.
#[ink(message)]
pub fn redeem(&mut self, attestation: attestation::Attestation) -> Result<()> {
// Verify the attestation
let data: GistQuote = self
.attestation_verifier
.verify_as(&attestation)
.ok_or(Error::InvalidSignature)?;
// The caller must be the attested account
if data.account_id != self.env().caller() {
return Err(Error::NoPermission);
}
if self.linked_users.contains(data.username) {
return Err(Error::UsernameAlreadyInUse);
}
let (contract, id) = self
.badge_contract_options
.as_mut()
.ok_or(Error::BadgeContractNotSetUp)?;
let badges: &IssuableRef = contract;
badges
.issue(*id, data.account_id)
.or(Err(Error::FailedToIssueBadge))
}
// Queries
/// Attests a Github Gist by the raw file url. (Query only)
///
/// It sends a HTTPS request to the url and extract an address from the claim ("This gist
/// is owned by address: 0x..."). Once the claim is verified, it returns a signed
/// attestation with the pair `(github_username, account_id)`.
#[ink(message)]
pub fn attest_gist(&self, url: String) -> Result<attestation::Attestation> {
// Verify the URL
let gist_url = parse_gist_url(&url)?;
// Fetch the gist content
let resposne = http_get!(url);
if resposne.status_code != 200 {
return Err(Error::RequestFailed);
}
let body = resposne.body;
// Verify the claim and extract the account id
let account_id = extract_claim(&body)?;
let quote = GistQuote {
username: gist_url.username,
account_id,
};
let result = self.attestation_generator.sign(quote);
Ok(result)
}
/// Helper query to return the account id of the current contract instance
#[ink(message)]
pub fn get_id(&self) -> AccountId {
self.env().account_id()
}
}
#[derive(PartialEq, Eq, Debug)]
struct GistUrl {
username: String,
gist_id: String,
filename: String,
}
#[derive(Clone, Encode, Decode, Debug)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct GistQuote {
username: String,
account_id: AccountId,
}
/// Parses a Github Gist url.
///
/// - Returns a parsed [GistUrl] struct if the input is a valid url;
/// - Otherwise returns an [Error].
fn parse_gist_url(url: &str) -> Result<GistUrl> {
let path = url
.strip_prefix("https://gist.githubusercontent.com/")
.ok_or(Error::InvalidUrl)?;
let components: Vec<_> = path.split('/').collect();
if components.len() < 5 {
return Err(Error::InvalidUrl);
}
Ok(GistUrl {
username: components[0].to_string(),
gist_id: components[1].to_string(),
filename: components[4].to_string(),
})
}
const CLAIM_PREFIX: &str = "This gist is owned by address: 0x";
const ADDRESS_LEN: usize = 64;
/// Extracts the ownerhip of the gist from a claim in the gist body.
///
/// A valid claim must have the statement "This gist is owned by address: 0x..." in `body`. The
/// address must be the 256 bits public key of the Substrate account in hex.
///
/// - Returns a 256-bit `AccountId` representing the owner account if the claim is valid;
/// - otherwise returns an [Error].
fn extract_claim(body: &[u8]) -> Result<AccountId> {
let body = String::from_utf8_lossy(body);
let pos = body.find(CLAIM_PREFIX).ok_or(Error::NoClaimFound)?;
let addr: String = body
.chars()
.skip(pos)
.skip(CLAIM_PREFIX.len())
.take(ADDRESS_LEN)
.collect();
let addr = addr.as_bytes();
let account_id = decode_accountid_256(addr)?;
Ok(account_id)
}
/// Decodes a hex string as an 256-bit AccountId32
fn decode_accountid_256(addr: &[u8]) -> Result<AccountId> {
use hex::FromHex;
if addr.len() != ADDRESS_LEN {
return Err(Error::InvalidAddressLength);
}
let bytes = <[u8; 32]>::from_hex(addr).or(Err(Error::InvalidAddress))?;
Ok(AccountId::from(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
use ink_env::AccountId;
use ink_lang as ink;
fn default_accounts() -> ink_env::test::DefaultAccounts<PinkEnvironment> {
ink_env::test::default_accounts::<Environment>()
}
fn set_next_caller(caller: AccountId) {
ink_env::test::set_caller::<Environment>(caller);
}
#[ink::test]
fn can_parse_gist_url() {
let result = parse_gist_url("https://gist.githubusercontent.com/h4x3rotab/0cabeb528bdaf30e4cf741e26b714e04/raw/620f958fb92baba585a77c1854d68dc986803b4e/test%2520gist");
assert_eq!(
result,
Ok(GistUrl {
username: "h4x3rotab".to_string(),
gist_id: "0cabeb528bdaf30e4cf741e26b714e04".to_string(),
filename: "test%2520gist".to_string(),
})
);
let err = parse_gist_url("http://example.com");
assert_eq!(err, Err(Error::InvalidUrl));
}
#[ink::test]
fn can_decode_claim() {
let ok = extract_claim(b"...This gist is owned by address: 0x0123456789012345678901234567890123456789012345678901234567890123...");
assert_eq!(
ok,
decode_accountid_256(
b"0123456789012345678901234567890123456789012345678901234567890123"
)
);
// Bad cases
assert_eq!(
extract_claim(b"This gist is owned by"),
Err(Error::NoClaimFound),
);
assert_eq!(
extract_claim(b"This gist is owned by address: 0xAB"),
Err(Error::InvalidAddressLength),
);
assert_eq!(
extract_claim(b"This gist is owned by address: 0xXX23456789012345678901234567890123456789012345678901234567890123"),
Err(Error::InvalidAddress),
);
}
#[ink::test]
fn end_to_end() {
use pink_extension::chain_extension::{mock, HttpResponse};
// Mock derive key call (a pregenerated key pair)
mock::mock_derive_sr25519_key(|_| {
hex::decode("78003ee90ff2544789399de83c60fa50b3b24ca86c7512d0680f64119207c80ab240b41344968b3e3a71a02c0e8b454658e00e9310f443935ecadbdd1674c683").unwrap()
});
mock::mock_get_public_key(|_| {
hex::decode("ce786c340288b79a951c68f87da821d6c69abd1899dff695bda95e03f9c0b012")
.unwrap()
});
mock::mock_sign(|_| b"mock-signature".to_vec());
mock::mock_verify(|_| true);
// Test accounts
let accounts = default_accounts();
use crate::issuable::mock_issuable;
use openbrush::traits::mock::{Addressable, ManagedCallStack};
use std::{cell::RefCell, rc::Rc};
let stack = ManagedCallStack::create_shared(accounts.alice);
mock_issuable::using(stack.clone(), || {
// Deploy a FatBadges contract
let badges = mock_issuable::deploy(fat_badges::FatBadges::new());
// Construct our contract (deployed by `accounts.alice` by default)
let contract = Addressable::create_native(1, EasyOracle::new(), stack);
// Create a badge and add the oracle contract as its issuer
let id = badges
.call_mut()
.new_badge("test-badge".to_string())
.unwrap();
assert!(badges
.call_mut()
.add_code(id, vec!["code1".to_string(), "code2".to_string()])
.is_ok());
assert!(badges.call_mut().add_issuer(id, contract.id()).is_ok());
// Tell the oracle the badges are ready to issue
assert!(contract.call_mut().config_issuer(badges.id(), id).is_ok());
// Generate an attestation
//
// Mock a http request first (the 256 bits account id is the pubkey of Alice)
mock::mock_http_request(|_| {
HttpResponse::ok(b"This gist is owned by address: 0x0101010101010101010101010101010101010101010101010101010101010101".to_vec())
});
let result = contract.call().attest_gist("https://gist.githubusercontent.com/h4x3rotab/0cabeb528bdaf30e4cf741e26b714e04/raw/620f958fb92baba585a77c1854d68dc986803b4e/test%2520gist".to_string());
assert!(result.is_ok());
let attestation = result.unwrap();
let data: GistQuote = Decode::decode(&mut &attestation.data[..]).unwrap();
assert_eq!(data.username, "h4x3rotab");
assert_eq!(data.account_id, accounts.alice);
// Before redeem
assert!(badges.call().get(id).is_err());
// Redeem and check if the contract as the code distributed
contract
.call_mut()
.redeem(attestation)
.expect("Should be able to issue badge");
assert_eq!(badges.call().get(id), Ok("code1".to_string()));
});
}
}
}