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
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use std::{
    fmt::Display,
    ops::{Deref, DerefMut},
    str::FromStr,
};

use data_encoding::Encoding;
use data_encoding_macro::new_encoding;
use fvm_shared2::address::Address as Address_v2;
use fvm_shared3::address::Address as Address_v3;
use fvm_shared4::address::Address as Address_v4;
use fvm_shared4::address::Address as Address_latest;
pub use fvm_shared4::address::{Error, Network, Payload, Protocol, PAYLOAD_HASH_LEN};
use integer_encoding::VarInt;
use num_traits::FromPrimitive;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU8, Ordering};

/// Zero address used to avoid allowing it to be used for verification.
/// This is intentionally disallowed because it is an edge case with Filecoin's BLS
/// signature verification.
// Copied from ref-fvm due to a bug in their definition.
pub static ZERO_ADDRESS: Lazy<Address> = Lazy::new(|| {
    Network::Mainnet
        .parse_address(
            "f3yaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaby2smx7a",
        )
        .unwrap()
        .into()
});

static GLOBAL_NETWORK: AtomicU8 = AtomicU8::new(Network::Mainnet as u8);

thread_local! {
    // Thread local network identifier. Defaults to value in GLOBAL_NETWORK.
    static LOCAL_NETWORK: AtomicU8 = AtomicU8::new(GLOBAL_NETWORK.load(Ordering::Acquire));
}

/// For user safety, Filecoin has different addresses for its mainnet and test networks: Mainnet
/// and testnet addresses are prefixed with `f` and `t`, respectively.
///
/// We use a thread-local variable to determine which format to use when parsing and pretty-printing
/// addresses. Note that the [`Address`] structure will parse both forms, while [`StrictAddress`]
/// will only succeed if the address has the correct network prefix.
///
/// The thread-local network variable is initialized to the value of the global network. This global
/// network variable is set once when Forest has figured out which network it is using.
pub struct CurrentNetwork();
impl CurrentNetwork {
    pub fn get() -> Network {
        FromPrimitive::from_u8(LOCAL_NETWORK.with(|ident| ident.load(Ordering::Acquire)))
            .unwrap_or(Network::Mainnet)
    }

    pub fn set(network: Network) {
        LOCAL_NETWORK.with(|ident| ident.store(network as u8, Ordering::Release));
    }

    pub fn set_global(network: Network) {
        GLOBAL_NETWORK.store(network as u8, Ordering::Release);
        CurrentNetwork::set(network);
    }

    #[cfg(test)]
    pub fn with<X>(network: Network, cb: impl FnOnce() -> X) -> X {
        let guard = NetworkGuard::new(network);
        let result = cb();
        drop(guard);
        result
    }

    #[cfg(test)]
    fn get_global() -> Network {
        FromPrimitive::from_u8(GLOBAL_NETWORK.load(Ordering::Acquire)).unwrap_or(Network::Mainnet)
    }
}

#[cfg(test)]
struct NetworkGuard(Network);
#[cfg(test)]
mod network_guard_impl {
    use super::*;

    impl NetworkGuard {
        pub fn new(new_network: Network) -> Self {
            let previous_network = CurrentNetwork::get();
            CurrentNetwork::set(new_network);
            NetworkGuard(previous_network)
        }
    }

    impl Drop for NetworkGuard {
        fn drop(&mut self) {
            CurrentNetwork::set(self.0);
        }
    }
}

/// A Filecoin address is an identifier that refers to an actor in the Filecoin state. All actors
/// (miner actors, the storage market actor, account actors) have an address. This address encodes
/// information about the network to which an actor belongs, the specific type of address encoding,
/// the address payload itself, and a checksum. The goal of this format is to provide a robust
/// address format that is both easy to use and resistant to errors.
///
/// Addresses are prefixed with either a mainnet tag or a testnet tag. The [`Address`] type will
/// parse both versions and discard the prefix. See also [`StrictAddress`].
///
/// For more information, see: <https://spec.filecoin.io/appendix/address/>
#[derive(
    Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(transparent)]
#[cfg_attr(test, derive(derive_quickcheck_arbitrary::Arbitrary))]
pub struct Address(Address_latest);

impl Address {
    pub const SYSTEM_ACTOR: Address = Address::new_id(0);
    pub const INIT_ACTOR: Address = Address::new_id(1);
    pub const REWARD_ACTOR: Address = Address::new_id(2);
    pub const CRON_ACTOR: Address = Address::new_id(3);
    pub const POWER_ACTOR: Address = Address::new_id(4);
    pub const MARKET_ACTOR: Address = Address::new_id(5);
    pub const VERIFIED_REGISTRY_ACTOR: Address = Address::new_id(6);
    pub const DATACAP_TOKEN_ACTOR: Address = Address::new_id(7);
    pub const ETHEREUM_ACCOUNT_MANAGER_ACTOR: Address = Address::new_id(10);
    pub const SAFT_ACTOR: Address = Address::new_id(122);
    pub const RESERVE_ACTOR: Address = Address::new_id(90);
    pub const CHAOS_ACTOR: Address = Address::new_id(98);
    pub const BURNT_FUNDS_ACTOR: Address = Address::new_id(99);

    pub const fn new_id(id: u64) -> Self {
        Address(Address_latest::new_id(id))
    }

    pub fn new_actor(data: &[u8]) -> Self {
        Address(Address_latest::new_actor(data))
    }

    pub fn new_bls(pubkey: &[u8]) -> Result<Self, Error> {
        Address_latest::new_bls(pubkey).map(Address::from)
    }

    pub fn new_secp256k1(pubkey: &[u8]) -> Result<Self, Error> {
        Address_latest::new_secp256k1(pubkey).map(Address::from)
    }

    pub fn new_delegated(ns: u64, subaddress: &[u8]) -> Result<Self, Error> {
        Ok(Self(Address_latest::new_delegated(ns, subaddress)?))
    }

    pub fn protocol(&self) -> Protocol {
        self.0.protocol()
    }

    pub fn into_payload(self) -> Payload {
        self.0.into_payload()
    }

    pub fn from_bytes(bz: &[u8]) -> Result<Self, Error> {
        Address_latest::from_bytes(bz).map(Address)
    }
}

impl FromStr for Address {
    type Err = <Address_latest as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Network::Testnet
            .parse_address(s)
            .or_else(|_| Network::Mainnet.parse_address(s))
            .map(Address::from)
    }
}

/// defines the encoder for `base32` encoding with the provided string with no padding
const ADDRESS_ENCODER: Encoding = new_encoding! {
    symbols: "abcdefghijklmnopqrstuvwxyz234567",
    padding: None,
};

impl Display for Address {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use fvm_shared4::address::CHECKSUM_HASH_LEN;
        const MAINNET_PREFIX: &str = "f";
        const TESTNET_PREFIX: &str = "t";

        let protocol = self.protocol();

        let prefix = if matches!(CurrentNetwork::get(), Network::Mainnet) {
            MAINNET_PREFIX
        } else {
            TESTNET_PREFIX
        };

        // write `fP` where P is the protocol number.
        write!(f, "{}{}", prefix, protocol)?;

        fn write_payload(
            f: &mut std::fmt::Formatter<'_>,
            protocol: Protocol,
            prefix: Option<&[u8]>,
            data: &[u8],
        ) -> std::fmt::Result {
            let mut hasher = blake2b_simd::Params::new()
                .hash_length(CHECKSUM_HASH_LEN)
                .to_state();
            hasher.update(&[protocol as u8]);
            if let Some(prefix) = prefix {
                hasher.update(prefix);
            }
            hasher.update(data);

            let mut buf = Vec::with_capacity(data.len() + CHECKSUM_HASH_LEN);
            buf.extend(data);
            buf.extend(hasher.finalize().as_bytes());

            f.write_str(&ADDRESS_ENCODER.encode(&buf))
        }

        match self.payload() {
            Payload::ID(id) => write!(f, "{}", id),
            Payload::Secp256k1(data) | Payload::Actor(data) => {
                write_payload(f, protocol, None, data)
            }
            Payload::BLS(data) => write_payload(f, protocol, None, data),
            Payload::Delegated(addr) => {
                write!(f, "{}f", addr.namespace())?;
                write_payload(
                    f,
                    protocol,
                    Some(&addr.namespace().encode_var_vec()),
                    addr.subaddress(),
                )
            }
        }
    }
}

impl Deref for Address {
    type Target = Address_latest;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Address {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// A Filecoin address is an identifier that refers to an actor in the Filecoin state. All actors
/// (miner actors, the storage market actor, account actors) have an address. This address encodes
/// information about the network to which an actor belongs, the specific type of address encoding,
/// the address payload itself, and a checksum. The goal of this format is to provide a robust
/// address format that is both easy to use and resistant to errors.
///
/// Addresses are prefixed with either a mainnet tag or a testnet tag. The [`StrictAddress`] type
/// will fail to parse addresses unless they have the correct tag indicated by [`CurrentNetwork`].
///
/// For more information, see: <https://spec.filecoin.io/appendix/address/>
#[derive(
    Copy,
    Clone,
    Debug,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    displaydoc::Display,
)]
#[serde(transparent)]
#[displaydoc("{0}")]
pub struct StrictAddress(pub Address);

impl FromStr for StrictAddress {
    type Err = <Address_latest as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let fvm_addr = CurrentNetwork::get().parse_address(s)?;
        Ok(StrictAddress(fvm_addr.into()))
    }
}

// Conversion implementations.
// Note for `::from_bytes`. Both FVM2 and FVM3 addresses values as bytes must be
// identical and able to do a conversion, otherwise it is a logic error and
// Forest should not continue so there is no point in `TryFrom`.

impl From<Address> for StrictAddress {
    fn from(other: Address) -> Self {
        StrictAddress(other)
    }
}

impl From<StrictAddress> for Address {
    fn from(other: StrictAddress) -> Self {
        other.0
    }
}

impl From<StrictAddress> for Address_v3 {
    fn from(other: StrictAddress) -> Self {
        other.0.into()
    }
}

impl From<StrictAddress> for Address_v4 {
    fn from(other: StrictAddress) -> Self {
        other.0.into()
    }
}

impl From<Address_v4> for Address {
    fn from(other: Address_v4) -> Self {
        Address(other)
    }
}

impl From<&Address_v4> for Address {
    fn from(other: &Address_v4) -> Self {
        Address(*other)
    }
}

impl From<&Address_v3> for Address {
    fn from(other: &Address_v3) -> Self {
        Address::from(
            Address_v4::from_bytes(&other.to_bytes()).unwrap_or_else(|e| {
                panic!("Couldn't convert from FVM3 address to FVM4 address: {other}, {e}")
            }),
        )
    }
}

impl From<Address_v3> for Address {
    fn from(other: Address_v3) -> Self {
        (&other).into()
    }
}

impl From<&Address_v2> for Address {
    fn from(other: &Address_v2) -> Self {
        Address::from(
            Address_v4::from_bytes(&other.to_bytes()).unwrap_or_else(|e| {
                panic!("Couldn't convert from FVM2 address to FVM4 address: {other}, {e}")
            }),
        )
    }
}

impl From<Address_v2> for Address {
    fn from(other: Address_v2) -> Self {
        (&other).into()
    }
}

impl From<Address> for Address_v4 {
    fn from(other: Address) -> Address_v4 {
        other.0
    }
}

impl From<&Address> for Address_v4 {
    fn from(other: &Address) -> Self {
        other.0
    }
}

impl From<&Address> for Address_v3 {
    fn from(other: &Address) -> Self {
        Address_v3::from_bytes(&other.to_bytes()).unwrap_or_else(|e| {
            panic!("Couldn't convert from FVM4 address to FVM3 address: {other}, {e}")
        })
    }
}

impl From<Address> for Address_v3 {
    fn from(other: Address) -> Self {
        (&other).into()
    }
}

impl From<&Address> for Address_v2 {
    fn from(other: &Address) -> Self {
        Address_v2::from_bytes(&other.to_bytes()).unwrap_or_else(|e| {
            panic!("Couldn't convert from FVM4 address to FVM2 address: {other}, {e}")
        })
    }
}

impl From<Address> for Address_v2 {
    fn from(other: Address) -> Address_v2 {
        (&other).into()
    }
}

#[cfg(test)]
fn flip_network(input: Network) -> Network {
    match input {
        Network::Mainnet => Network::Testnet,
        Network::Testnet => Network::Mainnet,
    }
}

#[test]
fn relaxed_address_parsing() {
    assert!(Address::from_str("t01234").is_ok());
    assert!(Address::from_str("f01234").is_ok());
}

#[test]
fn strict_address_parsing() {
    CurrentNetwork::with(Network::Mainnet, || {
        assert!(StrictAddress::from_str("f01234").is_ok());
        assert!(StrictAddress::from_str("t01234").is_err());
    });
    CurrentNetwork::with(Network::Testnet, || {
        assert!(StrictAddress::from_str("f01234").is_err());
        assert!(StrictAddress::from_str("t01234").is_ok());
    });
}

#[test]
fn set_with_network() {
    let outer_network = CurrentNetwork::get();
    let inner_network = flip_network(outer_network);
    CurrentNetwork::with(inner_network, || {
        assert_eq!(CurrentNetwork::get(), inner_network);
    });
    assert_eq!(outer_network, CurrentNetwork::get());
}

#[test]
fn unwind_current_network_on_panic() {
    let outer_network = CurrentNetwork::get();
    let inner_network = flip_network(outer_network);
    assert!(std::panic::catch_unwind(|| {
        CurrentNetwork::with(inner_network, || {
            panic!("unwinding stack");
        })
    })
    .is_err());
    let new_outer_network = CurrentNetwork::get();
    assert_eq!(outer_network, new_outer_network);
}

#[test]
fn inherit_global_network() {
    let outer_network = CurrentNetwork::get_global();
    let inner_network = flip_network(outer_network);
    CurrentNetwork::set_global(inner_network);
    std::thread::spawn(move || {
        assert_eq!(CurrentNetwork::get(), inner_network);
    })
    .join()
    .unwrap();
    CurrentNetwork::set_global(outer_network);
}