-
Notifications
You must be signed in to change notification settings - Fork 5
/
ledger.rs
365 lines (323 loc) · 9.98 KB
/
ledger.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
use std::{fmt::Display, rc::Rc};
use casper_node::types::Deploy;
use casper_types::bytesrepr::ToBytes;
use serde::{Deserialize, Serialize};
use crate::{message::CasperMessage, parser, sample::Sample};
// Character limit for Ledger's "label" row.
const LEDGER_VIEW_NAME_CHAR_COUNT: usize = 11;
// Character limit for Ledger's value top row.
const LEDGER_VIEW_TOP_ROW_CHAR_COUNT: usize = 17;
// Character limit for Ledger's value bottom row.
const LEDGER_VIEW_BOTTOM_CHAR_COUNT: usize = 17;
#[derive(Clone, Copy)]
pub(crate) enum TxnPhase {
Payment,
Session,
}
impl TxnPhase {
pub(crate) fn is_payment(&self) -> bool {
matches!(self, TxnPhase::Payment)
}
}
impl Display for TxnPhase {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TxnPhase::Payment => write!(f, "Payment"),
TxnPhase::Session => write!(f, "Execution"),
}
}
}
/// A single element of the transaction to be displayed in Ledger.
#[derive(Debug, Clone)]
pub(crate) struct Element {
/// Label of the element to display - like `from`, `to`, `amount`.
name: String,
/// Value of the element.
value: String,
// Whether to display in expert mode only.
expert: bool,
}
// Capitalizes the first character.
fn capitalize_first(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
impl Element {
/// Creates an instance of the element, marking it as to be displayed in expert-only mode.
pub(crate) fn expert(name: &str, value: String) -> Element {
Element {
name: capitalize_first(name),
value,
expert: true,
}
}
/// Creates an instance of the element, marking it as to be displayed in regular mode.
pub(crate) fn regular(name: &str, value: String) -> Self {
Element {
name: capitalize_first(name),
value,
expert: false,
}
}
/// Flips the "expert" bit to `true`.
pub(crate) fn as_expert(&mut self) {
self.expert = true;
}
}
#[derive(Clone)]
#[allow(unused)]
struct Ledger {
ledger_elements: Vec<Element>,
}
impl Ledger {
fn from_deploy(deploy: Deploy) -> Self {
Ledger {
ledger_elements: parser::parse_deploy(deploy),
}
}
fn from_message(casper_message: CasperMessage) -> Self {
Ledger {
ledger_elements: parser::parse_message(casper_message),
}
}
pub(crate) fn into_ledger_elements(self) -> impl Iterator<Item = Element> {
self.ledger_elements.into_iter()
}
}
#[derive(Default, Clone)]
struct LedgerValue {
top: String,
bottom: String,
}
impl LedgerValue {
// Adds a char to the ledger value.
// Single value is limited by the number of chars that can be
// printed on one ledger view: 34 char total in two lines.
// Function first tries to add a new char to the top row, if that is full
// then tries to add it to the bottom row.
// Returns whether adding char was successful.
fn add_char(&mut self, c: char) -> bool {
if self.top.chars().count() < LEDGER_VIEW_TOP_ROW_CHAR_COUNT {
self.top = format!("{}{}", self.top, c);
return true;
}
if self.bottom.chars().count() < LEDGER_VIEW_BOTTOM_CHAR_COUNT {
self.bottom = format!("{}{}", self.bottom, c);
return true;
}
false
}
// Concatenates both rows into single `String`.
fn into_str(&self) -> String {
format!("{}{}", self.top, self.bottom)
}
}
impl std::fmt::Display for LedgerValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}", self.top, self.bottom)
}
}
// Single Ledger page view representation.
// Example:
// Hash [1/2]
// 01001010101…
// 10101010101…
//
// When displayed can span multiple pages: 1/n
#[derive(Default, Clone)]
struct LedgerPageView {
// Name of the panel, like hash, chain name, sender, etc.
name: String,
// Whether element is for expert mode only.
expert: bool,
values: Vec<LedgerValue>,
}
impl LedgerPageView {
/// Parses an `Element` object (which represents a single piece of a transaction) into a Ledger representation -
/// including chopping up the string representation of the `Element` so that they can fit on a single Ledger screen.
fn from_element(element: Element) -> Self {
if element.name.chars().count() > LEDGER_VIEW_NAME_CHAR_COUNT {
panic!(
"Name tag can only be {} elements. Tag: {}",
LEDGER_VIEW_NAME_CHAR_COUNT, element.name
)
}
let mut values = vec![];
let mut curr_value = LedgerValue::default();
for c in element.value.chars() {
let added = curr_value.add_char(c);
if !added {
// Single ledger page can't contain more characters.
values.push(curr_value.clone());
// Create new Ledger page for that element.
curr_value = LedgerValue::default();
assert!(curr_value.add_char(c));
}
}
// Add the last view to the collection.
values.push(curr_value);
LedgerPageView {
name: element.name.clone(),
expert: element.expert,
values,
}
}
/// Turn the current element into printable Ledger views.
/// Adds indexes and labels.
fn to_string(&self) -> Vec<String> {
let total_count = self.values.len();
if total_count == 1 {
// The whole value can fit on one screen.
return vec![format!("{} : {}", self.name, self.values[0])];
}
let mut output = vec![];
// Split value display into multiple screens.
for (idx, value) in self.values.iter().enumerate() {
output.push(format!(
"{} [{}/{}] : {}",
self.name,
idx + 1, // Start with 1, not 0.
total_count,
value.into_str()
));
}
output
}
}
///
struct LedgerView {
pages: Vec<LedgerPageView>,
}
impl LedgerView {
fn from_ledger(ledger: Ledger) -> Self {
let pages = ledger
.into_ledger_elements()
.map(LedgerPageView::from_element)
.collect();
LedgerView { pages }
}
// Builds a vector of strings that follows the pattern:
// "0 | Type : Transfer",
// "1 | To [1/2] : 0101010101010101010101010101010101",
// "1 | To [2/2] : 010101010101010101010101010101",
// "2 | Amount : CSPR 24.5",
// "3 | Id : 999",
// "4 | Payment : "CSPR 1"
fn to_string(&self, expert: bool) -> Vec<String> {
let mut output = vec![];
for (idx, page) in self
.pages
.iter()
.filter(|page| if !page.expert { true } else { expert })
.enumerate()
{
let pages_str: Vec<String> = page
.to_string()
.into_iter()
.map(|page_str| format!("{} | {}", idx, page_str))
.collect();
output.extend(pages_str)
}
output
}
}
#[derive(Clone)]
#[allow(unused)]
pub(crate) struct LimitedLedgerConfig {
page_limit: u8,
on_regular: Rc<dyn Fn(&Ledger) -> Vec<String>>,
on_expert: Rc<dyn Fn(&Ledger) -> Vec<String>>,
}
impl LimitedLedgerConfig {
pub(crate) fn new(page_limit: u8) -> Self {
Self {
page_limit,
on_regular: Rc::new(Self::deploy_complexity_notice),
on_expert: Rc::new(Self::deploy_basic_info),
}
}
fn deploy_complexity_notice(_ledger: &Ledger) -> Vec<String> {
todo!()
}
fn deploy_basic_info(_ledger: &Ledger) -> Vec<String> {
todo!()
}
}
struct LimitedLedgerView<'a> {
_config: &'a LimitedLedgerConfig,
ledger: Ledger,
}
impl<'a> LimitedLedgerView<'a> {
fn new(config: &'a LimitedLedgerConfig, ledger: Ledger) -> Self {
Self {
_config: config,
ledger,
}
}
fn regular(&self) -> Vec<String> {
LedgerView::from_ledger(self.ledger.clone()).to_string(false)
}
fn expert(&self) -> Vec<String> {
LedgerView::from_ledger(self.ledger.clone()).to_string(true)
}
}
/// Representation of a test vector that is structures in the way that Zondax's pipelines expect it.
#[derive(Serialize, Deserialize)]
pub(super) struct ZondaxRepr {
index: usize,
name: String,
valid_regular: bool,
valid_expert: bool,
testnet: bool,
blob: String,
output: Vec<String>,
output_expert: Vec<String>,
}
/// Maps `Deploy` structure to the expected JSON representation.
pub(super) fn deploy_to_json(
index: usize,
sample_deploy: Sample<Deploy>,
config: &LimitedLedgerConfig,
) -> ZondaxRepr {
let (name, deploy, valid) = sample_deploy.destructure();
let blob = hex::encode(&deploy.to_bytes().unwrap());
let ledger = Ledger::from_deploy(deploy);
let ledger_view = LimitedLedgerView::new(config, ledger);
let output = ledger_view.regular();
let output_expert = ledger_view.expert();
ZondaxRepr {
index,
name,
valid_regular: valid,
valid_expert: valid,
testnet: true,
blob,
output,
output_expert,
}
}
pub(super) fn message_to_json(
index: usize,
sample_msg: Sample<CasperMessage>,
config: &LimitedLedgerConfig,
) -> ZondaxRepr {
let (name, message, valid) = sample_msg.destructure();
let blob = hex::encode(message.inner());
let ledger = Ledger::from_message(message);
let ledger_view = LimitedLedgerView::new(config, ledger);
let output = ledger_view.regular();
let output_expert = ledger_view.expert();
ZondaxRepr {
index,
name,
valid_regular: valid,
valid_expert: valid,
testnet: true,
blob,
output,
output_expert,
}
}