aboutsummaryrefslogtreecommitdiff
path: root/include/salticidae/stream.h
blob: 9e4791cea73d6e2d440d19438c6da17b76d186f6 (plain) (blame)
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
/**
 * Copyright (c) 2018 Cornell University.
 *
 * Author: Ted Yin <[email protected]>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef _SALTICIDAE_STREAM_H
#define _SALTICIDAE_STREAM_H

#include "salticidae/type.h"
#include "salticidae/ref.h"
#include "salticidae/crypto.h"

namespace salticidae {

template<size_t N, typename T> class Blob;
using uint256_t = Blob<256, uint64_t>;

class DataStream {
    bytearray_t buffer;
    size_t offset;

    public:
    DataStream(): offset(0) {}
    DataStream(const uint8_t *begin, const uint8_t *end): buffer(begin, end), offset(0) {}
    DataStream(bytearray_t &&data): buffer(std::move(data)), offset(0) {}
    DataStream(const bytearray_t &data): buffer(data), offset(0) {}

    DataStream(DataStream &&other):
            buffer(std::move(other.buffer)),
            offset(other.offset) {}

    DataStream(const DataStream &other):
        buffer(other.buffer),
        offset(other.offset) {}

    DataStream &operator=(const DataStream &other) {
        buffer = other.buffer;
        offset = other.offset;
        return *this;
    }

    DataStream &operator=(DataStream &&other) {
        buffer = std::move(other.buffer);
        offset = other.offset;
        return *this;
    }

    uint8_t *data() { return &buffer[offset]; }

    void clear() {
        buffer.clear();
        offset = 0;
    }

    size_t size() const {
        return buffer.size() - offset;
    }

    template<typename T>
    typename std::enable_if<std::is_integral<T>::value, DataStream &>::type
    operator<<(T d) {
        buffer.resize(buffer.size() + sizeof(T));
        *(reinterpret_cast<T *>(&*buffer.end() - sizeof(T))) = d;
        return *this;
    }

    template<typename T>
    typename std::enable_if<is_ranged<T>::value, DataStream &>::type
    operator<<(const T &d) {
        buffer.insert(buffer.end(), d.begin(), d.end());
        return *this;
    }

    void put_data(const uint8_t *begin, const uint8_t *end) {
        size_t len = end - begin;
        buffer.resize(buffer.size() + len);
        memmove(&*buffer.end() - len, begin, len);
    }

    const uint8_t *get_data_inplace(size_t len) {
        auto res = (uint8_t *)&*(buffer.begin() + offset);
#ifndef SALTICIDAE_NOCHECK
        if (offset + len > buffer.size())
            throw std::ios_base::failure("insufficient buffer");
#endif
        offset += len;
        return res;
    }

    template<typename T>
    typename std::enable_if<!is_ranged<T>::value &&
                            !std::is_integral<T>::value, DataStream &>::type
    operator<<(const T &obj) {
        obj.serialize(*this);
        return *this;
    }

    DataStream &operator<<(const char *cstr) {
        put_data((uint8_t *)cstr, (uint8_t *)cstr + strlen(cstr));
        return *this;
    }

    template<typename T>
    typename std::enable_if<std::is_integral<T>::value, DataStream &>::type
    operator>>(T &d) {
#ifndef SALTICIDAE_NOCHECK
        if (offset + sizeof(T) > buffer.size())
            throw std::ios_base::failure("insufficient buffer");
#endif
        d = *(reinterpret_cast<T *>(&buffer[offset]));
        offset += sizeof(T);
        return *this;
    }

    template<typename T>
    typename std::enable_if<!std::is_integral<T>::value, DataStream &>::type
    operator>>(T &obj) {
        obj.unserialize(*this);
        return *this;
    }

    std::string get_hex() const {
        char buf[3];
        DataStream s;
        for (auto it = buffer.begin() + offset; it != buffer.end(); it++)
        {
            sprintf(buf, "%02x", *it);
            s.put_data((uint8_t *)buf, (uint8_t *)buf + 2);
        }
        return std::string(s.buffer.begin(), s.buffer.end());
    }

    void load_hex(const std::string &hex_str) {
        size_t len = hex_str.size();
        const char *p;
        uint8_t *bp;
        unsigned int tmp;
        if (len & 1)
            throw std::invalid_argument("not a valid hex string");
        buffer.resize(len >> 1);
        offset = 0;
        for (p = hex_str.data(), bp = &*buffer.begin();
            p < hex_str.data() + len; p += 2, bp++)
        {
            if (sscanf(p, "%02x", &tmp) != 1)
                throw std::invalid_argument("not a valid hex string");
            *bp = tmp;
        }
    }

    operator bytearray_t () const & {
        return bytearray_t(buffer.begin() + offset, buffer.end());
    }

    operator bytearray_t () && {
        return std::move(buffer);
    }

    operator std::string () const & {
        return std::string(buffer.begin() + offset, buffer.end());
    }

    inline uint256_t get_hash() const;
};

template<size_t N, typename T = uint64_t>
class Blob {
    using _impl_type = T;
    static const size_t bit_per_datum = sizeof(_impl_type) * 8;
    static_assert(!(N % bit_per_datum), "N must be divisible by bit_per_datum");
    static const auto _len = N / bit_per_datum;
    _impl_type data[_len];
    bool loaded;

    public:

    Blob(): loaded(false) {}
    Blob(const bytearray_t &arr) {
        if (arr.size() != N / 8)
            throw std::invalid_argument("incorrect Blob size");
        load(&*arr.begin());
    }

    Blob(const uint8_t *arr) { load(arr); }

    void load(const uint8_t *arr) {
        arr += N / 8;
        for (_impl_type *ptr = data + _len; ptr > data;)
        {
            _impl_type x = 0;
            for (unsigned j = 0; j < sizeof(_impl_type); j++)
                x = (x << 8) | *(--arr);
            *(--ptr) = x;
        }
        loaded = true;
    }

    bool is_null() const { return !loaded; }

    bool operator==(const Blob<N> &other) const {
        for (size_t i = 0; i < _len; i++)
            if (data[i] != other.data[i])
                return false;
        return true;
    }

    bool operator!=(const Blob<N> &other) const {
        return !(*this == other);
    }

    size_t cheap_hash() const { return *data; }

    void serialize(DataStream &s) const {
        if (loaded)
        {
            for (const _impl_type *ptr = data; ptr < data + _len; ptr++)
                s << htole(*ptr);
        }
        else
        {
            for (const _impl_type *ptr = data; ptr < data + _len; ptr++)
                s << htole((_impl_type)0);
        }
    }

    void unserialize(DataStream &s) {
        for (_impl_type *ptr = data; ptr < data + _len; ptr++)
        {
            _impl_type x;
            s >> x;
            *ptr = letoh(x);
        }
        loaded = true;
    }

    operator bytearray_t () const & {
        DataStream s;
        s << *this;
        return std::move(s);
    }
};

template<typename T = uint64_t>
class Bits {
    using _impl_type = T;
    static const size_t bit_per_datum = sizeof(_impl_type) * 8;
    BoxObj<_impl_type[]> data;
    size_t nbits;
    size_t ndata;

    public:

    Bits(): data(nullptr) {}
    Bits(const bytearray_t &arr) {
        load(&*arr.begin(), arr.size());
    }

    Bits(const uint8_t *arr, size_t len) { load(arr, len); }
    Bits(size_t nbits): nbits(nbits) {
        ndata = (nbits + bit_per_datum - 1) / bit_per_datum;
        data = new _impl_type[ndata];
    }

    ~Bits() {}

    void load(const uint8_t *arr, size_t len) {
        nbits = len * 8;
        ndata = (len + sizeof(_impl_type) - 1) /
                        sizeof(_impl_type);
        data = new _impl_type[ndata];

        uint8_t *end = arr + len;
        for (_impl_type *ptr = data; ptr < data + ndata;)
        {
            _impl_type x = 0;
            for (unsigned j = 0, k = 0; j < sizeof(_impl_type); j++, k += 8)
                if (arr < end) x |= *(arr++) << k;
            *(ptr++) = x;
        }
    }

    bool is_null() const { return data == nullptr; }

    size_t cheap_hash() const { return *data; }

    void serialize(DataStream &s) const {
        s << htole(nbits);
        if (data)
        {
            for (const _impl_type *ptr = data; ptr < data + ndata; ptr++)
                s << htole(*ptr);
        }
        else
        {
            for (const _impl_type *ptr = data; ptr < data + ndata; ptr++)
                s << htole((_impl_type)0);
        }
    }

    void unserialize(DataStream &s) {
        _impl_type x;
        s >> x;
        nbits = letoh(x);
        ndata = (nbits + bit_per_datum - 1) / bit_per_datum;
        data = new _impl_type[ndata];
        for (_impl_type *ptr = data; ptr < data + ndata; ptr++)
        {
            s >> x;
            *ptr = letoh(x);
        }
    }

    operator bytearray_t () const & {
        DataStream s;
        s << *this;
        return std::move(s);
    }
};


const size_t ENT_HASH_LENGTH = 256 / 8;

uint256_t DataStream::get_hash() const {
    class SHA256 d;
    d.update(buffer.begin() + offset, size());
    return d.digest();
}

template<typename T> inline uint256_t get_hash(const T &x) {
    DataStream s;
    s << x;
    return s.get_hash();
}

template<typename T> inline std::string get_hex(const T &x) {
    DataStream s;
    s << x;
    return s.get_hex();
}

inline bytearray_t from_hex(const std::string &hex_str) {
    DataStream s;
    s.load_hex(hex_str);
    return std::move(s);
}

class Serializable {
    public:
    virtual ~Serializable() = default;
    virtual void serialize(DataStream &s) const = 0;
    virtual void unserialize(DataStream &s) = 0;

    virtual void from_bytes(const bytearray_t &raw_bytes) {
        DataStream s(raw_bytes);
        s >> *this;
    }

    virtual void from_bytes(bytearray_t &&raw_bytes) {
        DataStream s(std::move(raw_bytes));
        s >> *this;
    }


    virtual void from_hex(const std::string &hex_str) {
        DataStream s;
        s.load_hex(hex_str);
        s >> *this;
    }

    bytearray_t to_bytes() const {
        DataStream s;
        s << *this;
        return std::move(s);
    }

    std::string to_hex() const { return get_hex(*this); }
};

}

namespace std {
    template <>
    struct hash<salticidae::uint256_t> {
        size_t operator()(const salticidae::uint256_t &k) const {
            return (size_t)k.cheap_hash();
        }
    };

    template <>
    struct hash<const salticidae::uint256_t> {
        size_t operator()(const salticidae::uint256_t &k) const {
            return (size_t)k.cheap_hash();
        }
    };
}

#endif