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
//! Useful macros for implementing new chains

#[macro_export]
/// Implement `serde::Serialize` and `serde::Deserialize` by passing through to the hex
macro_rules! impl_hex_serde {
    ($item:ty) => {
        impl serde::Serialize for $item {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                let s = $crate::ser::ByteFormat::serialize_hex(self);
                serializer.serialize_str(&s)
            }
        }

        impl<'de> serde::Deserialize<'de> for $item {
            fn deserialize<D>(deserializer: D) -> Result<$item, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let s: &str = serde::Deserialize::deserialize(deserializer)?;
                <$item as $crate::ser::ByteFormat>::deserialize_hex(s)
                    .map_err(|e| serde::de::Error::custom(e.to_string()))
            }
        }
    };
}

#[macro_export]
/// Wrap a prefixed vector of bytes (`u8`) in a newtype, and implement convenience functions for
/// it.
macro_rules! wrap_prefixed_byte_vector {
    (
        $(#[$outer:meta])*
        $wrapper_name:ident
    ) => {
        $(#[$outer])*
        #[derive(Clone, Debug, Eq, PartialEq, Default, Hash, PartialOrd, Ord)]
        pub struct $wrapper_name(Vec<u8>);

        impl $crate::ser::ByteFormat for $wrapper_name {
            type Error = $crate::ser::SerError;

            fn serialized_length(&self) -> usize {
                let mut length = self.len();
                length += self.len_prefix() as usize;
                length
            }

            fn read_from<R>(reader: &mut R) -> Result<Self, Self::Error>
            where
                R: std::io::Read
            {
                Ok(coins_core::ser::read_prefix_vec(reader)?.into())
            }

            fn write_to<W>(&self, writer: &mut W) -> Result<usize, Self::Error>
            where
                W: std::io::Write
            {
                coins_core::ser::write_prefix_vec(writer, &self.0)
            }
        }

        impl_hex_serde!($wrapper_name);

        impl std::convert::AsRef<[u8]> for $wrapper_name {
            fn as_ref(&self) -> &[u8] {
                &self.0[..]
            }
        }

        impl $wrapper_name {
            /// Instantate a new wrapped vector
            pub fn new(v: Vec<u8>) -> Self {
                Self(v)
            }

            /// Construct an empty wrapped vector instance.
            pub fn null() -> Self {
                Self(vec![])
            }

            /// Return a reference to the underlying bytes
            pub fn items(&self) -> &[u8] {
                &self.0
            }

            /// Set the underlying items vector.
            pub fn set_items(&mut self, v: Vec<u8>) {
                self.0 = v
            }

            /// Push an item to the item vector.
            pub fn push(&mut self, i: u8) {
                self.0.push(i)
            }

            /// Return the length of the item vector.
            pub fn len(&self) -> usize {
                self.0.len()
            }

            /// Return true if the length of the item vector is 0.
            pub fn is_empty(&self) -> bool {
                self.len() == 0
            }

            /// Determine the byte-length of the vector length prefix
            pub fn len_prefix(&self) -> u8 {
                $crate::ser::prefix_byte_len(self.len() as u64)
            }

            /// Insert an item at the specified index.
            pub fn insert(&mut self, index: usize, i: u8) {
                self.0.insert(index, i)
            }
        }

        impl From<&[u8]> for $wrapper_name {
            fn from(v: &[u8]) -> Self {
                Self(v.to_vec())
            }
        }

        impl From<Vec<u8>> for $wrapper_name {
            fn from(v: Vec<u8>) -> Self {
                Self(v)
            }
        }

        impl std::ops::Index<usize> for $wrapper_name {
            type Output = u8;

            fn index(&self, index: usize) -> &Self::Output {
                &self.0[index]
            }
        }

        impl std::ops::Index<std::ops::Range<usize>> for $wrapper_name {
            type Output = [u8];

            fn index(&self, range: std::ops::Range<usize>) -> &[u8] {
                &self.0[range]
            }
        }

        impl std::ops::IndexMut<usize> for $wrapper_name {
            fn index_mut(&mut self, index: usize) -> &mut Self::Output {
                &mut self.0[index]
            }
        }

        impl std::iter::Extend<u8> for $wrapper_name {
            fn extend<I: std::iter::IntoIterator<Item=u8>>(&mut self, iter: I) {
                self.0.extend(iter)
            }
        }

        impl std::iter::IntoIterator for $wrapper_name {
            type Item = u8;
            type IntoIter = std::vec::IntoIter<u8>;

            fn into_iter(self) -> Self::IntoIter {
                self.0.into_iter()
            }
        }
    }
}

#[macro_export]
/// Implement conversion between script types by passing via `as_ref().into()`
macro_rules! impl_script_conversion {
    ($t1:ty, $t2:ty) => {
        impl From<&$t2> for $t1 {
            fn from(t: &$t2) -> $t1 {
                t.as_ref().into()
            }
        }
        impl From<&$t1> for $t2 {
            fn from(t: &$t1) -> $t2 {
                t.as_ref().into()
            }
        }
    };
}

#[macro_export]
/// Instantiate a new marked digest. Wraps the output of some type that implemented `digest::Digest`
macro_rules! marked_digest {
    (
        $(#[$outer:meta])*
        $marked_name:ident, $digest:ty
    ) => {
        $(#[$outer])*
        #[derive(Copy, Clone, Debug, Eq, PartialEq, Default, Hash, PartialOrd, Ord)]
        pub struct $marked_name($crate::hashes::DigestOutput<$digest>);

        impl $marked_name {
            /// Unwrap the marked digest, returning the underlying `GenericArray`
            pub fn to_internal(self) -> $crate::hashes::DigestOutput<$digest> {
                self.0
            }
        }

        impl $crate::hashes::MarkedDigestOutput for $marked_name {
            fn size(&self) -> usize {
                self.0.len()
            }
        }

        impl<T> From<T> for $marked_name
        where
            T: Into<$crate::hashes::DigestOutput<$digest>>
        {
            fn from(t: T) -> Self {
                $marked_name(t.into())
            }
        }

        impl $crate::hashes::MarkedDigest<$marked_name> for $digest {
            fn finalize_marked(self) -> $marked_name {
                $marked_name($crate::hashes::Digest::finalize(self))
            }

            fn digest_marked(data: &[u8]) -> $marked_name {
                $marked_name(<$digest as $crate::hashes::Digest>::digest(data))
            }
        }

        impl AsRef<$crate::hashes::DigestOutput<$digest>> for $marked_name {
            fn as_ref(&self) -> &$crate::hashes::DigestOutput<$digest> {
                &self.0
            }
        }

        impl AsMut<$crate::hashes::DigestOutput<$digest>> for $marked_name {
            fn as_mut(&mut self) -> &mut $crate::hashes::DigestOutput<$digest> {
                &mut self.0
            }
        }

        impl AsRef<[u8]> for $marked_name {
            fn as_ref(&self) -> &[u8] {
                self.0.as_ref()
            }
        }

        impl AsMut<[u8]> for $marked_name {
            fn as_mut(&mut self) -> &mut [u8] {
                self.0.as_mut()
            }
        }

        impl $crate::ser::ByteFormat for $marked_name {
            type Error = $crate::ser::SerError;

            fn serialized_length(&self) -> usize {
                $crate::hashes::MarkedDigestOutput::size(self)
            }

            fn read_from<R>(reader: &mut R) -> $crate::ser::SerResult<Self>
            where
                R: std::io::Read,
                Self: std::marker::Sized,
            {
                let mut buf = Self::default();
                reader.read_exact(buf.as_mut())?;
                Ok(buf)
            }

            fn write_to<W>(&self, writer: &mut W) -> $crate::ser::SerResult<usize>
            where
                W: std::io::Write,
            {
                Ok(writer.write(self.as_ref())?)
            }
        }
    };
}