-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathlib.rs
677 lines (594 loc) · 21 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.
//! For interacting with contracts from the command line, arguments need to be "transcoded" from
//! the string representation to the SCALE encoded representation.
//!
//! e.g. `"false" -> 0x00`
//!
//! And for displaying SCALE encoded data from events and RPC responses, it must be "transcoded"
//! in the other direction from the SCALE encoded representation to a human readable string.
//!
//! e.g. `0x00 -> "false"`
//!
//! Transcoding depends on [`scale-info`](https://github.com/paritytech/scale-info/) metadata in
//! order to dynamically determine the expected types.
//!
//! # Encoding
//!
//! First the string is parsed into an intermediate [`Value`]:
//!
//! `"false" -> Value::Bool(false)`
//!
//! This value is then matched with the metadata for the expected type in that context. e.g. the
//! [flipper](https://github.com/paritytech/ink/blob/master/examples/flipper/lib.rs) contract
//! accepts a `bool` argument to its `new` constructor, which will be reflected in the contract
//! metadata as [`scale_info::TypeDefPrimitive::Bool`].
//!
//! ```no_compile
//! #[ink(constructor)]
//! pub fn new(init_value: bool) -> Self {
//! Self { value: init_value }
//! }
//! ```
//!
//! The parsed `Value::Bool(false)` argument value is then matched with the
//! [`scale_info::TypeDefPrimitive::Bool`] type metadata, and then the value can be safely encoded
//! as a `bool`, resulting in `0x00`, which can then be appended as data to the message to invoke
//! the constructor.
//!
//! # Decoding
//!
//! First the type of the SCALE encoded data is determined from the metadata. e.g. the return type
//! of a message when it is invoked as a "dry run" over RPC:
//!
//! ```no_compile
//! #[ink(message)]
//! pub fn get(&self) -> bool {
//! self.value
//! }
//! ```
//!
//! The metadata will define the return type as [`scale_info::TypeDefPrimitive::Bool`], so that when
//! the raw data is received it can be decoded into the correct [`Value`], which is then converted
//! to a string for displaying to the user:
//!
//! `0x00 -> Value::Bool(false) -> "false"`
//!
//! # SCALE Object Notation (SCON)
//!
//! Complex types can be represented as strings using `SCON` for human-computer interaction. It is
//! intended to be similar to Rust syntax for instantiating types. e.g.
//!
//! `Foo { a: false, b: [0, 1, 2], c: "bar", d: (0, 1) }`
//!
//! This string could be parsed into a [`Value::Map`] and together with
//! [`scale_info::TypeDefComposite`] metadata could be transcoded into SCALE encoded bytes.
//!
//! As with the example for the primitive `bool` above, this works in the other direction for
//! decoding SCALE encoded bytes and converting them into a human readable string.
//!
//! # Example
//! ```no_run
//! # use contract_metadata::ContractMetadata;
//! # use contract_transcode::ContractMessageTranscoder;
//! # use std::{path::Path, fs::File};
//! let metadata_path = Path::new("/path/to/metadata.json");
//! let transcoder = ContractMessageTranscoder::load(metadata_path).unwrap();
//!
//! let constructor = "new";
//! let args = ["foo", "bar"];
//! let data = transcoder.encode(&constructor, &args).unwrap();
//!
//! println!("Encoded constructor data {:?}", data);
//! ```
mod decode;
mod encode;
pub mod env_types;
mod scon;
mod transcoder;
mod util;
pub use self::{
scon::{
Map,
Value,
},
transcoder::{
Transcoder,
TranscoderBuilder,
},
};
use anyhow::{
Context,
Result,
};
use ink_metadata::{
ConstructorSpec,
InkProject,
MessageSpec,
};
use scale::{
Compact,
Decode,
Input,
};
use scale_info::{
form::{
Form,
PortableForm,
},
Field,
};
use std::{
fmt::Debug,
fs::File,
path::Path,
};
/// Encode strings to SCALE encoded smart contract calls.
/// Decode SCALE encoded smart contract events and return values into `Value` objects.
pub struct ContractMessageTranscoder {
metadata: InkProject,
transcoder: Transcoder,
}
impl ContractMessageTranscoder {
pub fn new(metadata: InkProject) -> Self {
let transcoder = TranscoderBuilder::new(metadata.registry())
.register_custom_type_transcoder::<<ink_env::DefaultEnvironment as ink_env::Environment>::AccountId, _>(env_types::AccountId)
.register_custom_type_decoder::<<ink_env::DefaultEnvironment as ink_env::Environment>::Hash, _>(env_types::Hash)
.done();
Self {
metadata,
transcoder,
}
}
/// Attempt to create a [`ContractMessageTranscoder`] from the metadata file at the given path.
pub fn load<P>(metadata_path: P) -> Result<Self>
where
P: AsRef<Path>,
{
let path = metadata_path.as_ref();
let file = File::open(path)
.context(format!("Failed to open metadata file {}", path.display()))?;
let metadata: contract_metadata::ContractMetadata = serde_json::from_reader(file)
.context(format!(
"Failed to deserialize metadata file {}",
path.display()
))?;
let ink_metadata = serde_json::from_value(serde_json::Value::Object(
metadata.abi,
))
.context(format!(
"Failed to deserialize ink project metadata from file {}",
path.display()
))?;
Ok(Self::new(ink_metadata))
}
pub fn encode<I, S>(&self, name: &str, args: I) -> Result<Vec<u8>>
where
I: IntoIterator<Item = S>,
S: AsRef<str> + Debug,
{
let (selector, spec_args) = match (
self.find_constructor_spec(name),
self.find_message_spec(name),
) {
(Some(c), None) => (c.selector(), c.args()),
(None, Some(m)) => (m.selector(), m.args()),
(Some(_), Some(_)) => {
return Err(anyhow::anyhow!(
"Invalid metadata: both a constructor and message found with name '{}'",
name
))
}
(None, None) => {
return Err(anyhow::anyhow!(
"No constructor or message with the name '{}' found",
name
))
}
};
let mut encoded = selector.to_bytes().to_vec();
for (spec, arg) in spec_args.iter().zip(args) {
let value = scon::parse_value(arg.as_ref())?;
self.transcoder.encode(
self.metadata.registry(),
spec.ty().ty().id(),
&value,
&mut encoded,
)?;
}
Ok(encoded)
}
pub fn decode(&self, type_id: u32, input: &mut &[u8]) -> Result<Value> {
self.transcoder
.decode(self.metadata.registry(), type_id, input)
}
fn constructors(&self) -> impl Iterator<Item = &ConstructorSpec<PortableForm>> {
self.metadata.spec().constructors().iter()
}
fn messages(&self) -> impl Iterator<Item = &MessageSpec<PortableForm>> {
self.metadata.spec().messages().iter()
}
fn find_message_spec(&self, name: &str) -> Option<&MessageSpec<PortableForm>> {
self.messages().find(|msg| msg.label() == &name.to_string())
}
fn find_constructor_spec(
&self,
name: &str,
) -> Option<&ConstructorSpec<PortableForm>> {
self.constructors()
.find(|msg| msg.label() == &name.to_string())
}
pub fn decode_contract_event(&self, data: &mut &[u8]) -> Result<Value> {
// data is an encoded `Vec<u8>` so is prepended with its length `Compact<u32>`, which we
// ignore because the structure of the event data is known for decoding.
let _len = <Compact<u32>>::decode(data)?;
let variant_index = data.read_byte()?;
let event_spec = self
.metadata
.spec()
.events()
.get(variant_index as usize)
.ok_or_else(|| {
anyhow::anyhow!(
"Event variant {} not found in contract metadata",
variant_index
)
})?;
tracing::debug!("Decoding contract event '{}'", event_spec.label());
let mut args = Vec::new();
for arg in event_spec.args() {
let name = arg.label().to_string();
let value = self.decode(arg.ty().ty().id(), data)?;
args.push((Value::String(name), value));
}
let name = event_spec.label().to_string();
let map = Map::new(Some(&name), args.into_iter().collect());
Ok(Value::Map(map))
}
pub fn decode_contract_message(&self, data: &mut &[u8]) -> Result<Value> {
let mut msg_selector = [0u8; 4];
data.read(&mut msg_selector)?;
let msg_spec = self
.messages()
.find(|x| msg_selector == x.selector().to_bytes())
.ok_or_else(|| {
anyhow::anyhow!(
"Message with selector {} not found in contract metadata",
hex::encode(&msg_selector)
)
})?;
tracing::debug!("Decoding contract message '{}'", msg_spec.label());
let mut args = Vec::new();
for arg in msg_spec.args() {
let name = arg.label().to_string();
let value = self.decode(arg.ty().ty().id(), data)?;
args.push((Value::String(name), value));
}
let name = msg_spec.label().to_string();
let map = Map::new(Some(&name), args.into_iter().collect());
Ok(Value::Map(map))
}
pub fn decode_contract_constructor(&self, data: &mut &[u8]) -> Result<Value> {
let mut msg_selector = [0u8; 4];
data.read(&mut msg_selector)?;
let msg_spec = self
.constructors()
.find(|x| msg_selector == x.selector().to_bytes())
.ok_or_else(|| {
anyhow::anyhow!(
"Constructor with selector {} not found in contract metadata",
hex::encode(&msg_selector)
)
})?;
tracing::debug!("Decoding contract constructor '{}'", msg_spec.label());
let mut args = Vec::new();
for arg in msg_spec.args() {
let name = arg.label().to_string();
let value = self.decode(arg.ty().ty().id(), data)?;
args.push((Value::String(name), value));
}
let name = msg_spec.label().to_string();
let map = Map::new(Some(&name), args.into_iter().collect());
Ok(Value::Map(map))
}
pub fn decode_return(&self, name: &str, data: &mut &[u8]) -> Result<Value> {
let msg_spec = self.find_message_spec(name).ok_or_else(|| {
anyhow::anyhow!("Failed to find message spec with name '{}'", name)
})?;
if let Some(return_ty) = msg_spec.return_type().opt_type() {
self.decode(return_ty.ty().id(), data)
} else {
Ok(Value::Unit)
}
}
}
#[derive(Debug)]
pub enum CompositeTypeFields {
Named(Vec<CompositeTypeNamedField>),
Unnamed(Vec<Field<PortableForm>>),
NoFields,
}
#[derive(Debug)]
pub struct CompositeTypeNamedField {
name: <PortableForm as Form>::String,
field: Field<PortableForm>,
}
impl CompositeTypeNamedField {
pub fn name(&self) -> &str {
&self.name
}
pub fn field(&self) -> &Field<PortableForm> {
&self.field
}
}
impl CompositeTypeFields {
pub fn from_fields(fields: &[Field<PortableForm>]) -> Result<Self> {
if fields.iter().next().is_none() {
Ok(Self::NoFields)
} else if fields.iter().all(|f| f.name().is_some()) {
let fields = fields
.iter()
.map(|field| {
CompositeTypeNamedField {
name: field
.name()
.expect("All fields have a name; qed")
.to_owned(),
field: field.clone(),
}
})
.collect();
Ok(Self::Named(fields))
} else if fields.iter().all(|f| f.name().is_none()) {
Ok(Self::Unnamed(fields.to_vec()))
} else {
Err(anyhow::anyhow!(
"Struct fields should either be all named or all unnamed"
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use scale::Encode;
use scon::Value;
use std::str::FromStr;
use crate::scon::Hex;
use ink_lang as ink;
#[ink::contract]
pub mod transcode {
#[ink(storage)]
pub struct Transcode {
value: bool,
}
#[ink(event)]
pub struct Event1 {
#[ink(topic)]
name: Hash,
#[ink(topic)]
from: AccountId,
}
impl Transcode {
#[ink(constructor)]
pub fn new(init_value: bool) -> Self {
Self { value: init_value }
}
#[ink(constructor)]
pub fn default() -> Self {
Self::new(Default::default())
}
#[ink(message)]
pub fn flip(&mut self) {
self.value = !self.value;
}
#[ink(message)]
pub fn get(&self) -> bool {
self.value
}
#[ink(message)]
pub fn set_account_id(&self, account_id: AccountId) {
let _ = account_id;
}
#[ink(message)]
pub fn set_account_ids_vec(&self, account_ids: Vec<AccountId>) {
let _ = account_ids;
}
#[ink(message)]
pub fn primitive_vec_args(&self, args: Vec<u32>) {
let _ = args;
}
#[ink(message)]
pub fn uint_args(
&self,
_u8: u8,
_u16: u16,
_u32: u32,
_u64: u64,
_u128: u128,
) {
}
#[ink(message)]
pub fn uint_array_args(&self, arr: [u8; 4]) {
let _ = arr;
}
}
}
fn generate_metadata() -> ink_metadata::InkProject {
extern "Rust" {
fn __ink_generate_metadata() -> ink_metadata::InkProject;
}
let ink_project = unsafe { __ink_generate_metadata() };
ink_project
}
#[test]
fn encode_single_primitive_arg() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = transcoder.encode("new", &["true"])?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
assert_eq!(true.encode(), encoded_args);
Ok(())
}
#[test]
fn encode_account_id_custom_ss58_encoding() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = transcoder.encode(
"set_account_id",
&["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"],
)?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
let expected = sp_core::crypto::AccountId32::from_str(
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
)
.unwrap();
assert_eq!(expected.encode(), encoded_args);
Ok(())
}
#[test]
fn encode_account_ids_vec_args() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = transcoder.encode(
"set_account_ids_vec",
&["[5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty]"],
)?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
let expected = vec![
sp_core::crypto::AccountId32::from_str(
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
)
.unwrap(),
sp_core::crypto::AccountId32::from_str(
"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty",
)
.unwrap(),
];
assert_eq!(expected.encode(), encoded_args);
Ok(())
}
#[test]
fn encode_primitive_vec_args() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = transcoder.encode("primitive_vec_args", &["[1, 2]"])?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
let expected = vec![1, 2];
assert_eq!(expected.encode(), encoded_args);
Ok(())
}
#[test]
fn encode_uint_hex_literals() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = transcoder.encode(
"uint_args",
&[
"0x00",
"0xDEAD",
"0xDEADBEEF",
"0xDEADBEEF12345678",
"0xDEADBEEF0123456789ABCDEF01234567",
],
)?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
let expected = (
0x00u8,
0xDEADu16,
0xDEADBEEFu32,
0xDEADBEEF12345678u64,
0xDEADBEEF0123456789ABCDEF01234567u128,
);
assert_eq!(expected.encode(), encoded_args);
Ok(())
}
#[test]
fn encode_uint_arr_hex_literals() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded =
transcoder.encode("uint_array_args", &["[0xDE, 0xAD, 0xBE, 0xEF]"])?;
// encoded args follow the 4 byte selector
let encoded_args = &encoded[4..];
let expected: [u8; 4] = [0xDE, 0xAD, 0xBE, 0xEF];
assert_eq!(expected.encode(), encoded_args);
Ok(())
}
#[test]
fn decode_primitive_return() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded = true.encode();
let decoded = transcoder.decode_return("get", &mut &encoded[..])?;
assert_eq!(Value::Bool(true), decoded);
Ok(())
}
#[test]
fn decode_contract_event() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
// raw encoded event with event index prefix
let encoded = (0u8, [0u32; 32], [1u32; 32]).encode();
// encode again as a Vec<u8> which has a len prefix.
let encoded_bytes = encoded.encode();
let _ = transcoder.decode_contract_event(&mut &encoded_bytes[..])?;
Ok(())
}
#[test]
fn decode_hash_as_hex_encoded_string() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let hash = [
52u8, 40, 235, 225, 70, 245, 184, 36, 21, 218, 130, 114, 75, 207, 117, 240,
83, 118, 135, 56, 220, 172, 95, 131, 171, 125, 130, 167, 10, 15, 242, 222,
];
// raw encoded event with event index prefix
let encoded = (0u8, hash, [0u32; 32]).encode();
// encode again as a Vec<u8> which has a len prefix.
let encoded_bytes = encoded.encode();
let decoded = transcoder.decode_contract_event(&mut &encoded_bytes[..])?;
if let Value::Map(ref map) = decoded {
let name_field = &map[&Value::String("name".into())];
if let Value::Hex(hex) = name_field {
assert_eq!(&Hex::from_str("0x3428ebe146f5b82415da82724bcf75f053768738dcac5f83ab7d82a70a0ff2de")?, hex);
Ok(())
} else {
Err(anyhow::anyhow!(
"Expected a name field hash encoded as Hex value, was {:?}",
name_field
))
}
} else {
Err(anyhow::anyhow!(
"Expected a Value::Map for the decoded event"
))
}
}
#[test]
fn decode_contract_message() -> Result<()> {
let metadata = generate_metadata();
let transcoder = ContractMessageTranscoder::new(metadata);
let encoded_bytes = hex::decode("633aa551").unwrap();
let _ = transcoder.decode_contract_message(&mut &encoded_bytes[..])?;
Ok(())
}
}