-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
zen_octet.c
2035 lines (1898 loc) · 48.4 KB
/
zen_octet.c
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of Zenroom (https://zenroom.dyne.org)
*
* Copyright (C) 2017-2021 Dyne.org foundation
* designed, written and maintained by Denis Roio <jaromil@dyne.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
/// <h1>Base data type for cryptographic opearations</h1>
//
// Octets are <a
// href="https://en.wikipedia.org/wiki/First-class_citizen">first-class
// citizens</a> in Zenroom. They consist of arrays of bytes (8bit)
// compatible with all cryptographic functions and methods. They are
// implemented to avoid any buffer overflow and their maximum size is
// known at the time of instantiation. It is possible to create OCTET
// instances using the new() method:
//
// <code>message = OCTET.new(64) -- creates a 64 bytes long octet</code>
//
// The code above fills all 64 bytes with zeroes; to initialise with
// random data is possible to use the @{OCTET.random} function:
//
// <code>random = OCTET.random(32) -- creates a 32 bytes random octet</code>
//
// Octets can export their contents to a simple @{string} or more
// portable encodings as sequences of @{url64}, @{base64}, @{hex} or
// even @{bin} as sequences of binary 0 and 1. They can also be
// exported to Lua's @{array} format with one element per byte.
//
// @usage
// -- import a string as octet using the shortcut function str()
// hello = str("Hello, World!")
// -- print in various encoding formats
// print(hello:string()) -- print octet as string
// print(hello:hex()) -- print octet as hexadecimal sequence
// print(hello:base64()) -- print octet as base64
// print(hello:url64()) -- print octet as base64 url (preferred)
// print(hello:bin()) -- print octet as a sequence of 0 and 1
//
// @module OCTET
// @author Denis "Jaromil" Roio
// @license AGPLv3
// @copyright Dyne.org foundation 2017-2019
//
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <zen_error.h>
#include <lua_functions.h>
#include <amcl.h>
#include <zenroom.h>
#include <encoding.h>
#include <zen_memory.h>
#include <zen_octet.h>
#include <zen_big.h>
#include <zen_float.h>
#include <zen_ecp.h>
#include <math.h> // for log2 in entropy calculation
// from segwit_addr.c
extern int segwit_addr_encode(char *output, const char *hrp, int witver, const uint8_t *witprog, size_t witprog_len);
extern int segwit_addr_decode(int* witver, uint8_t* witdata, size_t* witdata_len, const char* hrp, const char* addr);
// from base58.c
extern int b58tobin(void *bin, size_t *binszp, const char *b58, size_t b58sz);
extern int b58enc(char *b58, size_t *b58sz, const void *data, size_t binsz);
// from zenroom types that are convertible to octet
// they don't do any internal memory allocation
// all arguments are allocated and freed by the caller
extern int _ecp_to_octet(octet *o, ecp *e);
extern int _ecp2_to_octet(octet *o, ecp2 *e);
static inline int _max(int x, int y) { if(x > y) return x; else return y; }
// static int _min(int x, int y) { if(x < y) return x; else return y; }
#include <ctype.h>
extern int _octet_to_big(lua_State *L, big *dst, octet *src);
// assumes null terminated string
// returns 0 if not base else length of base encoded string
int is_base64(const char *in) {
if(!in) { return 0; }
int c;
// check b64: header
// if(in[0]!='b' || in[1]!='6' || in[2]!='4' || in[3]!=':') return 0;
// check all valid characters
for(c=0; in[c]!='\0'; c++) {
if (!(isalnum(in[c])
|| '+' == in[c]
|| '=' == in[c]
|| '/' == in[c])) {
return 0; }
}
return c;
}
void push_octet_to_hex_string(lua_State *L, octet *o) {
char *s = malloc((o->len<<1)+1); // string len = double +1
buf2hex(s, o->val, o->len);
lua_pushstring(L,s);
free(s);
return;
}
extern const int8_t b58digits_map[];
// extern const char b58digits_ordered[];
int is_base58(lua_State *L, const char *in) {
if(!in) {
func(L, "null string in is_base58");
return 0; }
int c;
for(c=0; in[c]!='\0'; c++) {
if(b58digits_map[(int8_t)in[c]]==-1) {
func(L, "invalid base58 digit");
return 0; }
if(in[c] & 0x80) {
func(L, "high-bit set on invalid digit");
return 0; }
}
return c;
}
int is_hex(lua_State *L, const char *in) {
(void)L;
if(!in) { zerror(L, "Error in %s",__func__); return 0; }
if ( (in[0] == '0') && (in[1] == 'x') ) {
in+=2;
}
int c;
for(c=0; in[c]!=0; c++) {
if (!isxdigit(in[c])) {
return 0; }
}
return c;
}
// return total string length including spaces
int is_bin(lua_State *L, const char *in) {
(void)L;
if(!in) { zerror(L, "Error in %s",__func__); return 0; }
register int c;
register int len = 0;
for(c=0; in[c]!='\0'; c++) {
if (in[c]!='0' && in[c]!='1' && !isspace(in[c])) return 0;
len++;
}
return len;
}
// allocate octet without internally, no lua involved
octet* o_alloc(lua_State *L, int size) {
if(size<0) {
if(L) {
zerror(L, "Cannot create octet, size less than zero");
}
return NULL; }
if(size>MAX_OCTET) {
if(L) {
zerror(L, "Cannot create octet, size too big: %u", size);
}
return NULL; }
register int os = sizeof(octet);
octet *o = malloc(os);
if(!o) {
return NULL; }
Z(L);
Z->memcount_octets += os;
o->val = malloc(size +0x0f);
if(!o->val) {
return NULL; }
Z->memcount_octets += size+0x0f;
o->max = size;
o->len = 0;
o->val[0] = 0x0;
return(o);
}
void o_free(lua_State *L, octet *o) {
if(!o) return;
if(o->val) free(o->val);
Z(L);
Z->memcount_octets -= o->max + 0x0f + sizeof(octet);
free(o);
return;
}
// REMEMBER: newuserdata already pushes the object in lua's stack
octet* o_new(lua_State *L, const int size) {
if(size<0) {
zerror(L, "Cannot create octet, size less than zero");
return NULL; }
if(size>MAX_OCTET) {
zerror(L, "Cannot create octet, size too big: %u", size);
return NULL; }
octet *o = (octet *)lua_newuserdata(L, sizeof(octet));
if(!o) {
return NULL; }
luaL_getmetatable(L, "zenroom.octet");
lua_setmetatable(L, -2);
o->val = malloc(size +0x0f);
if(!o->val) {
return NULL; }
o->len = 0;
o->max = size;
// func(L, "new octet (%u bytes)",size);
return(o);
}
// here most internal type conversions happen
octet* o_arg(lua_State *L, int n) {
void *ud;
octet *o = NULL;
const char *type = luaL_typename(L, n);
o = (octet*) luaL_testudata(L, n, "zenroom.octet"); // new
if(o) {
if(o->len>MAX_OCTET) {
zerror(L, "argument %u octet too long: %u bytes", n, o->len);
return NULL;
} // allocate a new "internal" octet to be freed by caller
octet *r = o_alloc(L, o->len);
memcpy(r->val, o->val, o->len);
r->len = o->len;
return(r);
}
if(strlen(type) >= 6 && ((strncmp("string",type,6)==0)
|| (strncmp("number",type,6)==0)) ) {
size_t len; const char *str;
str = luaL_optlstring(L, n, "", &len);
if(len>MAX_OCTET) {
zerror(L, "invalid string size: %u", len);
return NULL;
}
// fallback to a string
o = o_alloc(L, len);
OCT_jstring(o, (char*)str); // null terminates and updates len
return(o);
}
// else
// zenroom types
ud = luaL_testudata(L, n, "zenroom.big");
if(ud) {
big *b = (big*)ud;
o = new_octet_from_big(L, b);
if(!o) {
zerror(L, "Could not allocate OCTET from BIG");
return NULL;
}
return(o);
}
ud = luaL_testudata(L, n, "zenroom.float");
if(ud) {
float *f = (float*)ud;
o = new_octet_from_float(L, f);
if(!o) {
zerror(L, "Could not allocate OCTET from FLOAT");
return NULL;
}
return(o);
}
ud = luaL_testudata(L, n, "zenroom.ecp");
if(ud) {
ecp *e = (ecp*)ud;
o = o_alloc(L, e->totlen);
if(!o) {
zerror(L, "Could not allocate OCTET from ECP");
return NULL;
}
_ecp_to_octet(o, e);
return(o);
}
ud = luaL_testudata(L, n, "zenroom.ecp2");
if(ud) {
ecp2 *e = (ecp2*)ud;
o = o_alloc(L, e->totlen);
if(!o) {
zerror(L, "Could not allocate OCTET from ECP2");
return NULL;
}
_ecp2_to_octet(o, e);
return(o);
}
if( lua_isnil(L, n) || lua_isnone(L, n) ) {
o = o_alloc(L, 1);
o->val[0] = 0x00;
o->len = 0;
return(o);
}
zerror(L, "Error in argument #%u", n);
return NULL;
// if executing here, something is pushed into Lua's stack
// but this is an internal function to gather arguments, so
// should be popped before returning the new octet
}
// allocates a new octet in LUA, duplicating the one in arg
octet *o_dup(lua_State *L, octet *o) {
octet *n = o_new(L, o->len);
if(!n) {
zerror(L, "Could not create OCTET");
return NULL;
}
OCT_copy(n,o);
return(n);
}
void push_buffer_to_octet(lua_State *L, char *p, size_t len) {
octet* o = o_new(L, len); SAFE(o);
// newuserdata already pushes the object in lua's stack
// memcpy(o->val, p, len);
register uint32_t i;
for (i=0; i<len; i++) o->val[i] = p[i];
o->len = len;
}
int o_destroy(lua_State *L) {
void *ud = luaL_testudata(L, 1, "zenroom.octet");
if(ud) {
octet *o = (octet*)ud;
if(o->val) free(o->val);
}
// free(o);
return 0;
}
/// Global OCTET Functions
// @section OCTET
//
// The "global OCTET functions" are all prefixed by <b>OCTET.</b>
// (please note the separator is a "." dot) and always return a new
// octet resulting from the operation.
//
// This is a difference with "object methods" listed in the next
// section which are operating on the octet itself, doing "in place"
// modifications. Plan well what to use to save memory space and
// computations.
/***
Create a new octet with a specified maximum size, or a default if
omitted. All operations exceeding the octet's size will truncate
excessing data. Octets cannot be resized.
@function OCTET.new(length)
@int[opt=64] length maximum length in bytes
@return octet newly instantiated octet
*/
static int newoctet (lua_State *L) {
BEGIN();
char *failed_msg = NULL;
octet *o = o_arg(L, 1);
if(!o) {
failed_msg = "Could not create OCTET";
goto end;
}
octet *r = o_dup(L, (octet*)o);
if(!r) {
failed_msg = "Could not duplicate OCTET";
goto end;
}
(void)r;
end:
o_free(L, o);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/***
Create a new octet of size 0
@function OCTET.empty()
@return octet newly instantiated octet
*/
static int new_empty_octet (lua_State *L) {
BEGIN();
char *failed_msg = NULL;
octet *o = o_alloc(L, 0);
if(!o) {
failed_msg = "Could not allocate OCTET";
goto end;
}
if(!o_dup(L, o)){
failed_msg = "Could not duplicate OCTET";
goto end;
}
end:
o_free(L, o);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
static int filloctet(lua_State *L) {
BEGIN();
int i;
octet *o = (octet*) luaL_testudata(L, 1, "zenroom.octet");
SAFE(o);
octet *fill = (octet*) luaL_testudata(L, 2, "zenroom.octet");
SAFE(fill);
for(i=0; i<o->max; i++)
o->val[i] = fill->val[i % fill->len];
o->len = o->max;
END(0);
}
/***
Bitwise XOR operation on two octets, returns a new octet. This is also
executed when using the '<b>~</b>' operator between two
octets. Results in a newly allocated octet, does not change the
contents of any other octet involved.
@param dest leftmost octet used in XOR operation
@param source rightmost octet used in XOR operation
@function OCTET.xor(dest, source)
@return a new octet resulting from the operation
*/
static int xor_n(lua_State *L) {
BEGIN();
char *failed_msg = NULL;
octet *x = o_arg(L, 1);
octet *y = o_arg(L, 2);
if(!x || !y) {
failed_msg = "Could not allocate OCTET";
goto end;
}
octet *n = o_new(L,_max(x->len, y->len));
if(!n) {
failed_msg = "Could not create OCTET";
goto end;
}
OCT_copy(n, x);
OCT_xor(n, y);
end:
o_free(L, x);
o_free(L, y);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
static int lua_is_base64(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_base64(s);
if(len<4) {
lua_pushboolean(L, 0);
func(L, "string is not a valid base64 sequence");
END(1); }
lua_pushboolean(L, 1);
END(1);
}
static int lua_is_url64(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_url64(s);
if(len<3) {
lua_pushboolean(L, 0);
func(L, "string is not a valid url64 sequence");
END(1); }
lua_pushboolean(L, 1);
END(1);
}
static int lua_is_base58(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_base58(L, s);
if(!len) {
lua_pushboolean(L, 0);
func(L, "string is not a valid base58 sequence");
END(1); }
lua_pushboolean(L, 1);
END(1);
}
static int lua_is_hex(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_hex(L, s);
if(!len) {
lua_pushboolean(L, 0);
func(L, "string is not a valid hex sequence");
END(1); }
lua_pushboolean(L, 1);
END(1);
}
static int lua_is_bin(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_bin(L, s);
if(!len) {
lua_pushboolean(L, 0);
func(L, "string is not a valid binary sequence");
END(1); }
lua_pushboolean(L, 1);
END(1);
}
// to emulate 128bit counters, de facto truncate integers to 64bit
typedef struct { uint64_t high, low; } uint128_t;
static int from_number(lua_State *L) {
BEGIN();
// number argument, import
int tn;
lua_Number n = lua_tointegerx(L,1,&tn);
if(!tn) {
lerror(L, "O.from_number input is not a number");
return 0; }
const uint64_t v = floorf(n);
octet *o = o_new(L, 16); SAFE(o);
// conversion from int64 to binary
// TODO: check endian portability issues
register uint8_t i = 0;
register char *d = o->val;
for(i=0;i<8;i++,d++) *d = 0x0;
register char *p = (char*) &v;
d+=7;
for(i=0;i<8;i++,d--,p++) *d=*p;
o->len = 16;
END(1);
}
/*
@function OCTET.from_rawlen(string, length) (unsafe!)
@str string string to copy in octet as-is
@int length string length in bytes
@return octet newly instantiated octet
*/
static int from_rawlen (lua_State *L) {
BEGIN();
const char *s;
size_t len;
s = lua_tolstring(L, 1, &len); /* get result */
luaL_argcheck(L, s != NULL, 1, "string expected");
int tn;
lua_Number n = lua_tointegerx(L,2,&tn);
if(!tn) {
lerror(L, "O.new 2nd arg is not a number");
return 0; }
octet *o = o_new(L, (int)n); SAFE(o);
register int c;
for(c=0;c<n;c++) o->val[c] = s[c];
o->len = (int)n;
END(1);
}
static int from_base64(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "base64 string expected");
int len = is_base64(s);
if(!len) {
lerror(L, "base64 string contains invalid characters");
return 0; }
int nlen = len + len + len;
octet *o = o_new(L, nlen); // 4 byte header
SAFE(o);
OCT_frombase64(o, (char*)s);
END(1);
}
static int from_url64(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "url64 string expected");
int len = is_url64(s);
if(!len) {
lerror(L, "url64 string contains invalid characters");
return 0; }
int nlen = B64decoded_len(len);
// func(L,"U64 decode len: %u -> %u",len,nlen);
octet *o = o_new(L, nlen); SAFE(o);
o->len = U64decode(o->val, (char*)s);
// func(L,"u64 return len: %u",o->len);
END(1);
}
static int from_base58(lua_State *L) {
BEGIN();
char *failed_msg = NULL;
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "base58 string expected");
int len = is_base58(L, s);
if(!len) {
lerror(L, "base58 string contains invalid characters");
return 0; }
size_t binmax = B64decoded_len(len); //((len + 3) >> 2) *3;
char *tmp = malloc(binmax);
// size_t binmax = len + len + len;
size_t binlen = binmax;
if(!b58tobin((void*)tmp, &binlen, s, len)) {
failed_msg = "Error in conversion from base58";
goto end; }
octet *o = o_new(L, binlen);
if(!o) {
failed_msg = "Could not create OCTET";
goto end;
}
if(binlen>binmax) {
memcpy(o->val,&tmp[binlen-binmax],binmax);
} else {
memcpy(o->val,&tmp[binmax-binlen],binlen);
}
o->len = binlen;
end:
free(tmp);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
static int from_string(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
const int len = strlen(s);
// STRING SIZE CHECK before import to OCTET
if(len > MAX_OCTET) {
zerror(L, "%s: invalid string size: %u", __func__, len);
lerror(L, "operation aborted");
return 0; }
octet *o = o_new(L, len); SAFE(o);
register int i = 0;
for(i=0;s[i];i++) o->val[i]=s[i];
o->len = i;
END(1);
}
static int from_hex(lua_State *L) {
BEGIN();
char *s = (char*)lua_tostring(L, 1);
if(!s) {
zerror(L, "%s :: invalid argument", __func__); // fatal
lua_pushboolean(L, 0);
END(1); }
int len;
if ( (s[0] == '0') && (s[1] == 'x') )
len = is_hex(L, s+2);
else len = is_hex(L, s);
if(!len) {
zerror(L, "hex sequence invalid"); // fatal
lua_pushboolean(L, 0);
END(1); }
func(L,"hex string sequence length: %u",len);
if(!len || len>MAX_FILE<<1) { // *2 hex tuples
zerror(L, "hex sequence too long: %u bytes", len<<1); // fatal
lua_pushboolean(L, 0);
END(1); }
octet *o = o_new(L, len>>1); SAFE(o);
if ( (s[0] == '0') && (s[1] == 'x') ) {
// ethereum elides the leftmost 0 char when value <= 0F
if((len&1)==1) { // odd length means elision
s[1]='0'; // overwrite a single byte in const
o->len = hex2buf(o->val, s+1);
} else {
o->len = hex2buf(o->val, s+2);
}
} else {
o->len = hex2buf(o->val,s);
}
if(o->len < 0) {
zerror(L, "%s :: Invalid octet in hex string", __func__);
lerror(L, "operation aborted");
lua_pushnil(L);
}
END(1);
}
// I'm quite happy about this: its fast and secure. It can just be
// made more elegant.
static int from_bin(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "binary string sequence expected");
const int len = is_bin(L, s);
if(!len || len > MAX_FILE) {
zerror(L, "invalid binary sequence size: %u", len);
lerror(L, "operation aborted");
return 0; }
octet *o = o_new(L, len+4); SAFE(o);
register char *S = (char*)s;
register int p; // position in whole string
register int i; // increased only when 1 or 0 is found
register int d; // increased only added to dest
register int j; // bytemask counter
volatile uint8_t b = 0x0; // bytemask
for(p=0, j=0, i=0, d=0; p<len; p++, S++) {
if(isspace(*S)) continue;
if(j<7) { // add to bytemask
if(*S=='1') b = b | 0x1;
b = b<<1;
j++;
} else { // reset bytemask and shift left
if(*S=='1') b = b | 0x1;
o->val[d] = b;
b = 0x0;
j = 0;
d++;
}
i++;
}
o->val[d] = 0x0;
o->len = d;
END(1);
}
/*
In the bitcoin world, addresses are the hash of the public key (binary data).
However, the user usually knows them in some encoded form (which also include
some error check mechanism, to improve security against typos). Bech32 is the
format used with segwit transactions.
@param s Address encoded as Bech32(m)
@treturn[1] Address as binary data
@treturn[2] Segwit version (version 0 is Bech32, version >0 is Bechm)
*/
static int from_segwit_address(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
if(!s) {
zerror(L, "%s :: invalid argument", __func__); // fatal
lua_pushboolean(L, 0);
END(1); }
int witver;
uint8_t witprog[40];
size_t witprog_len;
const char* hrp = "bc";
int ret = segwit_addr_decode(&witver, witprog, &witprog_len, hrp, s);
if(!ret) {
hrp = "tb";
ret = segwit_addr_decode(&witver, witprog, &witprog_len, hrp, s);
}
if(!ret) {
zerror(L, "%s :: not bech32 address", __func__);
lua_pushboolean(L, 0);
END(1);
}
octet *o = o_new(L, witprog_len); SAFE(o);
register size_t i;
for(i=0; i<witprog_len; i++) {
o->val[i] = (char)witprog[i];
}
o->len = witprog_len;
lua_pushinteger(L,witver);
END(2);
}
/*
For an introduction see `from_segwit_address`
HRP (human readble part) are the first characters of the address, they can
be bc (bitcoin network) or tb (testnet network)
@param o Address in binary format (octet with the result of the hash160)
@param witver Segwit version
@param s HRP
@return Bech32(m) encoded string
*/
static int to_segwit_address(lua_State *L) {
BEGIN();
char *failed_msg = NULL, *result = NULL;
octet *o = o_arg(L,1);
if(!o) {
failed_msg = "Could not allocate OCTET";
goto end;
}
if(!o->len) { lua_pushnil(L); goto end; }
int tn;
lua_Number witver = lua_tointegerx(L, 2, &tn);
if(!tn) {
failed_msg = "segwit version is not a number";
goto end;
}
const char *s = lua_tostring(L, 3);
if(!s) {
failed_msg = "Invalid 3rd argument";
goto end;
}
if(witver < 0 || witver > 16) {
zerror(L, "Invalid segwit version: %d", witver);
failed_msg = "Invalid segwit version";
goto end;
}
if(o->len < 2 || o->len > 40) {
zerror(L, "Invalid size for segwit address: %d", o->len);
failed_msg = "Invalid size for segwit address";
goto end;
}
// HRP to lower case
// the string the user pass could be longer than 2 characters
// and it could be either lower case of upper case
// First of all I normalize it:
// - it can be at most 2 chars
// - it must be lower case
char hrp[3];
register int i = 0;
while(i < 2 && s[i] != '\0') {
if(s[i] > 'A' && s[i] < 'Z') {
hrp[i] = s[i] - 'A' + 'a'; // to lower case
} else {
hrp[i] = s[i];
}
i++;
}
hrp[i] = '\0';
if(s[i] != '\0' || (strncmp(hrp, "bc", 2) != 0 && strncmp(hrp, "tb", 2) != 0)) {
zerror(L, "Invalid human readable part: %s", s);
failed_msg = "Invalid human readable part";
goto end;
}
result = malloc(73+strlen(hrp));
if (!segwit_addr_encode(result, hrp, witver, (uint8_t*)o->val, o->len)) {
failed_msg = "Cannot be encoded to segwit format";
goto end;
}
lua_pushstring(L,result);
end:
free(result);
o_free(L, o);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
static int to_mnemonic(lua_State *L) {
BEGIN();
octet *o = o_arg(L,1); SAFE(o);
if(!o->len) { lua_pushnil(L); o_free(L,o); return 1; }
if(o->len > 32) {
zerror(L, "%s :: octet bigger than 32 bytes cannot be encoded to mnemonic");
o_free(L,o);
lua_pushboolean(L, 0);
END(0);
}
char *result = malloc(24 * 10);
if(mnemonic_from_data(result, o->val, o->len)) {
lua_pushstring(L, result);
} else {
zerror(L, "%s :: cannot be encoded to mnemonic", __func__);
lua_pushboolean(L, 0);
}
o_free(L,o);
free(result);
END(1);
}
static int from_mnemonic(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
if(!s) {
zerror(L, "%s :: invalid argument", __func__); // fatal
lua_pushboolean(L, 0);
END(1); }
// From bip39 it can be at most 32bytes
octet *o = o_alloc(L, 32); SAFE(o);
if(!mnemonic_check_and_bits(s, &(o->len), o->val)) {
zerror(L, "%s :: words cannot be encoded with bip39 format", __func__);
lua_pushboolean(L, 0);
goto end;
}
o_dup(L, o); // push in lua's stack
end:
o_free(L, o);
END(1);
}
/***
Concatenate two octets, returns a new octet. This is also executed
when using the '<b>..</b>' operator btween two octets. It results in a
newly allocated octet, does not change the contents of other octets.
@param dest leftmost octet will be overwritten by result
@param source rightmost octet used in XOR operation
@function OCTET.concat(dest, source)
@return a new octet resulting from the operation
*/
static int concat_n(lua_State *L) {
BEGIN();
char *failed_msg = NULL;
octet *x = NULL, *y = NULL;
char *sx = NULL, *sy = NULL;
octet xs, ys;
void *ud;
ud = luaL_testudata(L, 1, "zenroom.octet");
if(ud) {
x = o_arg(L, 1);
if(!x) {
failed_msg = "Could not allocate OCTET";
goto end;
}
} else {
x = &xs;
sx = (char*) lua_tostring(L, 1);
if(!sx) {
failed_msg = "octet or string expected in concat";
goto end;
}
xs.len = strlen(sx);
xs.val = sx;
}
ud = luaL_testudata(L, 2, "zenroom.octet");
if(ud) {
y = o_arg(L, 2);
if(!y) {
failed_msg = "Could not allocate OCTET";
goto end;
}
} else {
y = &ys;
sy = (char*) lua_tostring(L, 2);
if(!sy) {
failed_msg = "octet or string expected in concat";
goto end;
}
ys.len = strlen(sy);
ys.val = sy;
}
octet *n = o_new(L, x->len+y->len);
if(!n) {
failed_msg = "Could not create OCTET";
goto end;
}
OCT_copy(n, x);
OCT_joctet(n, y);
end:
o_free(L, y);
o_free(L, x);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/// Object Methods
// @type OCTET
//
// This section lists methods that can be called as members of the
// <b>OCTET:</b> objects, using a ":" semicolon notation instead of a
// dot. Example synopsis:
//
// <pre class="example">
// random = OCTET.random(32) -- global OCTET constructor using the dot
// print( random:<span class="global">hex</span>() ) -- method call on the created object using the colon
// </pre>
//
// In the example above we create a new "random" OCTET variable with
// 32 bytes of randomness, then call the ":hex()" method on it to print
// it out as an hexadecimal sequence.
//
// The contents of an octet object are never changed this way: methods
// always return a new octet with the requested changes applied.
//
/***
Print an octet in base64 notation.
@function octet:base64()
@return a string representing the octet's contents in base64
@see octet:hex
@usage
-- This method as well :string() and :hex() can be used both to set
-- from and print out in particular formats.