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
//! Utilities for testing smart contracts.
use std::collections::BTreeMap;

use oasis_contract_sdk_crypto as crypto;
use oasis_runtime_sdk::crypto::signature;

use crate::{
    context::Context,
    env::{Crypto, Env},
    event::Event,
    storage::{ConfidentialStore, PublicStore, Store},
    types::{
        address::Address,
        env::{QueryRequest, QueryResponse},
        event::Event as RawEvent,
        message::Message,
        token, CallFormat, ExecutionContext, InstanceId,
    },
};

/// Mock store.
#[derive(Clone, Default)]
pub struct MockStore {
    inner: BTreeMap<Vec<u8>, Vec<u8>>,
}

impl MockStore {
    /// Create a new empty mock store.
    pub fn new() -> Self {
        Self {
            inner: BTreeMap::new(),
        }
    }
}

impl Store for MockStore {
    fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
        self.inner.get(key).cloned()
    }

    fn insert(&mut self, key: &[u8], value: &[u8]) {
        self.inner.insert(key.to_owned(), value.to_owned());
    }

    fn remove(&mut self, key: &[u8]) {
        self.inner.remove(key);
    }
}

impl PublicStore for MockStore {}
impl ConfidentialStore for MockStore {}

/// Mock environment.
#[derive(Clone, Default)]
pub struct MockEnv {}

impl MockEnv {
    /// Create a new mock environment.
    pub fn new() -> Self {
        Self {}
    }
}

impl Env for MockEnv {
    fn query<Q: Into<QueryRequest>>(&self, query: Q) -> QueryResponse {
        match query.into() {
            QueryRequest::BlockInfo => QueryResponse::BlockInfo {
                round: 42,
                epoch: 2,
                timestamp: 100_000,
            },
            _ => unimplemented!(),
        }
    }

    fn address_for_instance(&self, instance_id: InstanceId) -> Address {
        let b = [
            "test_12345678".as_bytes(),
            &instance_id.as_u64().to_be_bytes(),
        ]
        .concat();
        Address::from_bytes(&b).unwrap()
    }

    #[cfg(feature = "debug-utils")]
    fn debug_print(&self, msg: &str) {
        eprintln!("{}", msg);
    }
}

impl Crypto for MockEnv {
    fn ecdsa_recover(&self, input: &[u8]) -> [u8; 65] {
        crypto::ecdsa::recover(input).unwrap()
    }

    fn signature_verify_ed25519(&self, key: &[u8], message: &[u8], signature: &[u8]) -> bool {
        let key = if let Ok(key) = signature::ed25519::PublicKey::from_bytes(key) {
            key
        } else {
            return false;
        };
        let sig: signature::Signature = signature.to_vec().into();
        key.verify_raw(message, &sig).is_ok()
    }

    fn signature_verify_secp256k1(&self, key: &[u8], message: &[u8], signature: &[u8]) -> bool {
        let key = if let Ok(key) = signature::secp256k1::PublicKey::from_bytes(key) {
            key
        } else {
            return false;
        };
        let sig: signature::Signature = signature.to_vec().into();
        key.verify_raw(message, &sig).is_ok()
    }

    fn signature_verify_sr25519(
        &self,
        key: &[u8],
        context: &[u8],
        message: &[u8],
        signature: &[u8],
    ) -> bool {
        let key = if let Ok(key) = signature::sr25519::PublicKey::from_bytes(key) {
            key
        } else {
            return false;
        };
        let sig: signature::Signature = signature.to_vec().into();
        key.verify(context, message, &sig).is_ok()
    }
}

/// A mock contract context suitable for testing.
pub struct MockContext {
    /// Execution context.
    pub ec: ExecutionContext,

    /// Public store.
    pub public_store: MockStore,
    /// "Confidential" store.
    pub confidential_store: MockStore,
    /// Environment.
    pub env: MockEnv,

    /// Emitted messages.
    pub messages: Vec<Message>,
    /// Emitted events.
    pub events: Vec<RawEvent>,
}

impl From<ExecutionContext> for MockContext {
    fn from(ec: ExecutionContext) -> Self {
        Self {
            ec,
            public_store: MockStore::new(),
            confidential_store: MockStore::new(),
            env: MockEnv::new(),
            messages: Vec::new(),
            events: Vec::new(),
        }
    }
}

impl Context for MockContext {
    type PublicStore = MockStore;
    type ConfidentialStore = MockStore;
    type Env = MockEnv;

    fn instance_id(&self) -> InstanceId {
        self.ec.instance_id
    }

    fn instance_address(&self) -> &Address {
        &self.ec.instance_address
    }

    fn caller_address(&self) -> &Address {
        &self.ec.caller_address
    }

    fn deposited_tokens(&self) -> &[token::BaseUnits] {
        &self.ec.deposited_tokens
    }

    fn is_read_only(&self) -> bool {
        self.ec.read_only
    }

    fn call_format(&self) -> CallFormat {
        self.ec.call_format
    }

    fn emit_message(&mut self, msg: Message) {
        self.messages.push(msg);
    }

    fn emit_event<E: Event>(&mut self, event: E) {
        self.events.push(event.into_raw());
    }

    fn public_store(&mut self) -> &mut Self::PublicStore {
        &mut self.public_store
    }

    fn confidential_store(&mut self) -> &mut Self::ConfidentialStore {
        &mut self.confidential_store
    }

    fn env(&self) -> &Self::Env {
        &self.env
    }
}

/// A macro that creates Oasis ABI entry points.
#[macro_export]
#[doc(hidden)]
macro_rules! __create_contract {
    ($name:ty) => {};
}