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
mod errors;
mod network;
mod payload;
mod protocol;
pub use self::errors::Error;
pub use self::network::Network;
pub use self::payload::{BLSPublicKey, Payload};
pub use self::protocol::Protocol;
use data_encoding::Encoding;
#[allow(unused_imports)]
use data_encoding_macro::{internal_new_encoding, new_encoding};
use encoding::{blake2b_variable, serde_bytes, Cbor};
use once_cell::sync::OnceCell;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::hash::Hash;
use std::str::FromStr;
use std::{borrow::Cow, fmt};
const ADDRESS_ENCODER: Encoding = new_encoding! {
symbols: "abcdefghijklmnopqrstuvwxyz234567",
padding: None,
};
pub const PAYLOAD_HASH_LEN: usize = 20;
pub const SECP_PUB_LEN: usize = 65;
pub const BLS_PUB_LEN: usize = 48;
pub const CHECKSUM_HASH_LEN: usize = 4;
const MAX_ADDRESS_LEN: usize = 84 + 2;
const MAINNET_PREFIX: &str = "f";
const TESTNET_PREFIX: &str = "t";
#[cfg(feature = "json")]
const UNDEF_ADDR_STRING: &str = "<empty>";
pub static NETWORK_DEFAULT: OnceCell<Network> = OnceCell::new();
#[derive(PartialEq, Eq, Clone, Debug, Hash, Copy)]
pub struct Address {
network: Network,
payload: Payload,
}
impl Address {
fn new(network: Network, protocol: Protocol, bz: &[u8]) -> Result<Self, Error> {
Ok(Self {
network,
payload: Payload::new(protocol, bz)?,
})
}
pub fn from_bytes(bz: &[u8]) -> Result<Self, Error> {
if bz.len() < 2 {
Err(Error::InvalidLength)
} else {
let protocol = Protocol::from_byte(bz[0]).ok_or(Error::UnknownProtocol)?;
Self::new(
*NETWORK_DEFAULT.get_or_init(|| Network::Mainnet),
protocol,
&bz[1..],
)
}
}
pub fn new_id(id: u64) -> Self {
Self {
network: *NETWORK_DEFAULT.get_or_init(|| Network::Mainnet),
payload: Payload::ID(id),
}
}
pub fn new_secp256k1(pubkey: &[u8]) -> Result<Self, Error> {
if pubkey.len() != 65 {
return Err(Error::InvalidSECPLength(pubkey.len()));
}
Ok(Self {
network: *NETWORK_DEFAULT.get_or_init(|| Network::Mainnet),
payload: Payload::Secp256k1(address_hash(pubkey)),
})
}
pub fn new_actor(data: &[u8]) -> Self {
Self {
network: *NETWORK_DEFAULT.get_or_init(|| Network::Mainnet),
payload: Payload::Actor(address_hash(data)),
}
}
pub fn new_bls(pubkey: &[u8]) -> Result<Self, Error> {
if pubkey.len() != BLS_PUB_LEN {
return Err(Error::InvalidBLSLength(pubkey.len()));
}
let mut key = [0u8; BLS_PUB_LEN];
key.copy_from_slice(pubkey);
Ok(Self {
network: *NETWORK_DEFAULT.get_or_init(|| Network::Mainnet),
payload: Payload::BLS(key.into()),
})
}
pub fn protocol(&self) -> Protocol {
Protocol::from(self.payload)
}
pub fn payload(&self) -> &Payload {
&self.payload
}
pub fn into_payload(self) -> Payload {
self.payload
}
pub fn payload_bytes(&self) -> Vec<u8> {
self.payload.to_raw_bytes()
}
pub fn network(&self) -> Network {
self.network
}
pub fn set_network(&mut self, network: Network) -> &mut Self {
self.network = network;
self
}
pub fn to_bytes(self) -> Vec<u8> {
self.payload.to_bytes()
}
pub fn id(&self) -> Result<u64, Error> {
match self.payload {
Payload::ID(id) => Ok(id),
_ => Err(Error::NonIDAddress),
}
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", encode(self))
}
}
impl FromStr for Address {
type Err = Error;
fn from_str(addr: &str) -> Result<Self, Error> {
if addr.len() > MAX_ADDRESS_LEN || addr.len() < 3 {
return Err(Error::InvalidLength);
}
let network: Network = match addr.get(0..1).ok_or(Error::UnknownNetwork)? {
TESTNET_PREFIX => Network::Testnet,
MAINNET_PREFIX => Network::Mainnet,
_ => {
return Err(Error::UnknownNetwork);
}
};
let protocol: Protocol = match addr.get(1..2).ok_or(Error::UnknownProtocol)? {
"0" => Protocol::ID,
"1" => Protocol::Secp256k1,
"2" => Protocol::Actor,
"3" => Protocol::BLS,
_ => {
return Err(Error::UnknownProtocol);
}
};
let raw = addr.get(2..).ok_or(Error::InvalidPayload)?;
if protocol == Protocol::ID {
if raw.len() > 20 {
return Err(Error::InvalidLength);
}
let id = raw.parse::<u64>()?;
return Ok(Address {
network,
payload: Payload::ID(id),
});
}
let mut payload = ADDRESS_ENCODER.decode(raw.as_bytes())?;
let cksm = payload.split_off(payload.len() - CHECKSUM_HASH_LEN);
if (protocol == Protocol::Secp256k1 || protocol == Protocol::Actor)
&& payload.len() != PAYLOAD_HASH_LEN
{
return Err(Error::InvalidPayload);
}
if protocol == Protocol::BLS && payload.len() != BLS_PUB_LEN {
return Err(Error::InvalidPayload);
}
let mut ingest = payload.clone();
ingest.insert(0, protocol as u8);
if !validate_checksum(&ingest, cksm) {
return Err(Error::InvalidChecksum);
}
Address::new(network, protocol, &payload)
}
}
impl Serialize for Address {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let address_bytes = self.to_bytes();
serde_bytes::Serialize::serialize(&address_bytes, s)
}
}
impl<'de> Deserialize<'de> for Address {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bz: Cow<'de, [u8]> = serde_bytes::Deserialize::deserialize(deserializer)?;
Address::from_bytes(&bz).map_err(de::Error::custom)
}
}
impl Cbor for Address {}
fn encode(addr: &Address) -> String {
match addr.protocol() {
Protocol::Secp256k1 | Protocol::Actor | Protocol::BLS => {
let ingest = addr.to_bytes();
let mut bz = addr.payload_bytes();
bz.extend(checksum(&ingest));
format!(
"{}{}{}",
addr.network.to_prefix(),
addr.protocol().to_string(),
ADDRESS_ENCODER.encode(bz.as_mut()),
)
}
Protocol::ID => format!(
"{}{}{}",
addr.network.to_prefix(),
addr.protocol().to_string(),
from_leb_bytes(&addr.payload_bytes()).expect("should read encoded bytes"),
),
}
}
pub(crate) fn to_leb_bytes(id: u64) -> Result<Vec<u8>, Error> {
let mut buf = Vec::new();
leb128::write::unsigned(&mut buf, id)?;
Ok(buf)
}
pub(crate) fn from_leb_bytes(bz: &[u8]) -> Result<u64, Error> {
let mut readable = bz;
let id = leb128::read::unsigned(&mut readable)?;
if to_leb_bytes(id)? == bz {
Ok(id)
} else {
Err(Error::InvalidAddressIDPayload(bz.to_owned()))
}
}
#[cfg(test)]
mod tests {
use crate::{errors::Error, from_leb_bytes, to_leb_bytes};
#[test]
fn test_from_leb_bytes_passing() {
let passing = vec![67];
assert_eq!(
to_leb_bytes(from_leb_bytes(&passing).unwrap()),
Ok(vec![67])
);
}
#[test]
fn test_from_leb_bytes_extra_bytes() {
let extra_bytes = vec![67, 0, 1, 2];
match from_leb_bytes(&extra_bytes) {
Ok(id) => {
println!(
"Successfully decoded bytes when it was not supposed to. Result was: {:?}",
&to_leb_bytes(id).unwrap()
);
panic!();
}
Err(e) => {
assert_eq!(e, Error::InvalidAddressIDPayload(extra_bytes));
}
}
}
#[test]
fn test_from_leb_bytes_minimal_encoding() {
let minimal_encoding = vec![67, 0, 130, 0];
match from_leb_bytes(&minimal_encoding) {
Ok(id) => {
println!(
"Successfully decoded bytes when it was not supposed to. Result was: {:?}",
&to_leb_bytes(id).unwrap()
);
panic!();
}
Err(e) => {
assert_eq!(e, Error::InvalidAddressIDPayload(minimal_encoding));
}
}
}
}
pub fn checksum(ingest: &[u8]) -> Vec<u8> {
blake2b_variable(ingest, CHECKSUM_HASH_LEN)
}
pub fn validate_checksum(ingest: &[u8], expect: Vec<u8>) -> bool {
let digest = checksum(ingest);
digest == expect
}
fn address_hash(ingest: &[u8]) -> [u8; 20] {
let digest = blake2b_variable(ingest, PAYLOAD_HASH_LEN);
let mut hash = [0u8; 20];
hash.clone_from_slice(&digest);
hash
}
#[cfg(feature = "json")]
pub mod json {
use super::*;
use serde::{Deserialize, Deserializer, Serializer};
use std::borrow::Cow;
#[derive(Deserialize, Serialize)]
#[serde(transparent)]
pub struct AddressJson(#[serde(with = "self")] pub Address);
#[derive(Serialize)]
#[serde(transparent)]
pub struct AddressJsonRef<'a>(#[serde(with = "self")] pub &'a Address);
impl From<Address> for AddressJson {
fn from(address: Address) -> Self {
Self(address)
}
}
impl From<AddressJson> for Address {
fn from(address: AddressJson) -> Self {
address.0
}
}
pub fn serialize<S>(m: &Address, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&encode(m))
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Address, D::Error>
where
D: Deserializer<'de>,
{
let address_as_string: Cow<'de, str> = Deserialize::deserialize(deserializer)?;
Address::from_str(&address_as_string).map_err(de::Error::custom)
}
#[cfg(feature = "json")]
pub mod vec {
use super::*;
use crate::json::{AddressJson, AddressJsonRef};
use forest_json_utils::GoVecVisitor;
use serde::ser::SerializeSeq;
#[derive(Deserialize, Serialize)]
#[serde(transparent)]
pub struct AddressJsonVec(#[serde(with = "self")] pub Vec<Address>);
#[derive(Serialize)]
#[serde(transparent)]
pub struct AddressJsonSlice<'a>(#[serde(with = "self")] pub &'a [Address]);
pub fn serialize<S>(m: &[Address], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(m.len()))?;
for e in m {
seq.serialize_element(&AddressJsonRef(e))?;
}
seq.end()
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Address>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(GoVecVisitor::<Address, AddressJson>::new())
}
}
pub mod opt {
use super::*;
use serde::{self, Deserialize, Deserializer, Serializer};
use std::borrow::Cow;
pub fn serialize<S>(v: &Option<Address>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(unwrapped_address) = v.as_ref() {
serializer.serialize_str(&encode(unwrapped_address))
} else {
serializer.serialize_str(UNDEF_ADDR_STRING)
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Address>, D::Error>
where
D: Deserializer<'de>,
{
let address_as_string: Cow<'de, str> = Deserialize::deserialize(deserializer)?;
if address_as_string == UNDEF_ADDR_STRING {
return Ok(None);
}
Ok(Some(
Address::from_str(&address_as_string).map_err(de::Error::custom)?,
))
}
}
}