-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathzen_octet.c
More file actions
3243 lines (2987 loc) · 89.1 KB
/
Copy pathzen_octet.c
File metadata and controls
3243 lines (2987 loc) · 89.1 KB
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-2026 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>Array of raw bytes: base data type in Zenroom</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 <errno.h>
#include <zen_error.h>
#include <lua_functions.h>
#include <amcl.h>
#include <encoding.h>
#include <zen_error.h>
#include <zen_octet.h>
#include <zen_big.h>
#include <zen_float.h>
#include <zen_time.h>
#include <zen_fuzzer.h>
#include <zen_ecp.h>
#include <math.h> // for log2 in entropy calculation
#include <zenroom.h>
// 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, const octet *src);
// helper function to take as input optional number without throwing an error
lua_Number optnumber_nullable(lua_State *L, int idx, lua_Number def, int *isvalid) {
if(lua_isnoneornil(L, idx)) {
*isvalid = 1;
return def;
}
int isnum;
lua_Number n = lua_tonumberx(L, idx, &isnum);
if(!isnum) {
*isvalid = 0;
return 0;
}
*isvalid = 1;
return n;
}
//
void push_octet_to_hex_string(lua_State *L, octet *o) {
// string len = double +1
char *s = zmalloc((o->len<<1)+1); SAFEV(s, MALLOC_ERROR);
buf2hex(s, o->val, o->len);
lua_pushstring(L,s);
zfree(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 an octet without pushing it to the lua stack
octet* o_alloc(lua_State *L, int size) {
if(HEDLEY_UNLIKELY(size<0)) {
zerror(L, "Cannot create octet, size less than zero");
return NULL; }
if(HEDLEY_UNLIKELY(size>MAX_OCTET)) {
zerror(L, "Cannot create octet, size too big: %u", size);
return NULL; }
register int os = sizeof(octet);
octet *o = zmalloc(os);
if(!o) {
zerror(L, "Cannot create octet, malloc failure: %s",
strerror(errno));
return NULL; }
zenroom_t *Z = zen_get_context(L);
o->val = zmalloc(size +0x0f);
if(!o->val) {
zerror(L, "Cannot create octet value, malloc: %s",
strerror(errno));
return NULL; }
o->max = size;
o->len = 0;
o->val[0] = 0x0;
o->ref = 0;
return(o);
}
void o_free(lua_State *L, const octet *o) {
(void)L;
if(HEDLEY_UNLIKELY(o==NULL)) return; // accepts NULL args with no errors
octet *t = (octet*)o; // remove const static check
t->ref--;
if(t->ref>0) return;
if(HEDLEY_LIKELY(t->val!=NULL)) {
zfree(t->val);
t->val = NULL;
}
// Heap-allocated octets (from o_alloc) have ref=0 initially;
// after decrement ref==-1 → free the struct.
// Userdata-backed octets (from o_new) have ref=1 initially;
// after o_arg increments and GC/o_free decrements, ref reaches
// 0 here. Lua GC manages the userdata struct; do NOT free it.
if(t->ref < 0)
zfree(t);
}
// REMEMBER: newuserdata already pushes the object in lua's stack
octet* o_new(lua_State *L, const int size) {
if(HEDLEY_UNLIKELY(size<0)) {
zerror(L, "Cannot create octet, size less than zero");
return NULL; }
if(HEDLEY_UNLIKELY(size>MAX_OCTET)) {
zerror(L, "Cannot create octet, size too big: %u", size);
return NULL; }
octet *o = (octet *)lua_newuserdata(L, sizeof(octet));
if(HEDLEY_UNLIKELY(o==NULL)) {
zerror(L, "Cannot create octet, lua_newuserdata failure");
return NULL; }
luaL_getmetatable(L, "zenroom.octet");
lua_setmetatable(L, -2);
o->val = zmalloc(size +0x0f);
if(HEDLEY_UNLIKELY(o->val==NULL)) {
zerror(L, "Cannot create octet, malloc failure");
zerror(L, "%s: %s",__func__,strerror(errno));
return NULL; }
o->len = 0;
o->max = size;
o->ref = 1;
// func(L, "new octet (%u bytes)",size);
return(o);
}
// here most internal type conversions happen
const 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
o->ref++; // signal we are reusing the same pointer
return(o);
}
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: %lu", 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.time");
if(ud) {
ztime_t *b = (ztime_t*)ud;
o = new_octet_from_time(L, *b);
if(!o) {
zerror(L, "Could not allocate OCTET from TIME");
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, const octet *o) {
octet *n = o_new(L, o->len);
if(!n) {
zerror(L, "Could not create OCTET");
return NULL;
}
OCT_copy(n,(octet*)o);
return(n);
}
// push a new octet without allocating new buffer but reusing the one
// in arg. does not reuse o_new or o_alloc, does no new buffer alloc.
octet *o_push(lua_State *L, const char *buf, size_t len) {
if(HEDLEY_UNLIKELY(buf==NULL)) {
zerror(L, "Cannot push octet, null ptr");
return(NULL);
}
// newuserdata already pushes the object in lua's stack
octet *o = (octet *)lua_newuserdata(L, sizeof(octet));
if(HEDLEY_UNLIKELY(o==NULL)) {
zerror(L, "Cannot create octet, lua_newuserdata failure");
return(NULL);
}
luaL_getmetatable(L, "zenroom.octet");
lua_setmetatable(L, -2);
o->val = (char*)buf; // allocated by caller, freed by gc
o->len = len;
o->max = len;
o->ref = 1;
return(o);
}
// extern const char *o_val(const octet*);
// extern size_t o_len(const octet*);
HEDLEY_PURE const char *o_val(const octet *o) { return((const char*)o->val); }
HEDLEY_PURE size_t o_len(const octet *o) { return(o->len); }
void push_buffer_to_octet(lua_State *L, char *p, size_t len) {
octet* o = o_new(L, len); SAFEV(o, CREATE_OCT_ERR);
// 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;
}
// pushes a null-terminated string to a new octet and keeps its
// null-termination
void push_string_to_octet(lua_State *L, char *p) {
octet* o = o_new(L, strlen(p)+1); SAFEV(o, CREATE_OCT_ERR);
strcpy(o->val,p);
o->len = o->max-1;
}
int o_destroy(lua_State *L) {
void *ud = luaL_testudata(L, 1, "zenroom.octet");
if(!ud) return 0;
octet *o = (octet*)ud;
o->ref--;
if(o->ref > 0) return 0;
if(o->val) {
zfree(o->val);
o->val = NULL;
}
// zfree(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
@int[opt=64] length maximum length in bytes
@return octet newly instantiated octet
*/
static int newoctet (lua_State *L) {
BEGIN();
char *failed_msg = NULL;
const octet *o = o_arg(L, 1); SAFE_GOTO(o, ALLOCATE_OCT_ERR);
octet *r = o_dup(L, (octet*)o); SAFE_GOTO(r, DUPLICATE_OCT_ERR);
(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); SAFE_GOTO(o, ALLOCATE_OCT_ERR);
SAFE_GOTO(o_dup(L, o), DUPLICATE_OCT_ERR);
end:
o_free(L, o);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/***
Generate an octet of specified length containing random bytes.
@function OCTET.random
@param len a specified length
@return random octet of specified length
*/
static int new_random(lua_State *L) {
BEGIN();
int tn;
lua_Number n = lua_tonumberx(L, 1, &tn);
octet *o = o_new(L,(int)n); SAFE(o, CREATE_OCT_ERR);
zenroom_t *Z = zen_get_context(L);
OCT_rand(o, Z->random_generator, (int)n);
END(1);
}
/***
Check if a Lua string is a valid base64-encoded string.
*If the string is valid base64, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_base64
@param s a Lua string
@return a boolean value
*/
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);
}
/***
Check if a Lua string is a valid url64-encoded string.
*If the string is valid url64, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_url64
@param s a Lua string
@return a boolean value
*/
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);
}
/***
Check if a Lua string is a valid base58-encoded string.
*If the string is valid base58, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_base58
@param s a Lua string
@return a boolean value
*/
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);
}
/***
Check if a Lua string is a valid hexadecimal-encoded string.
*If the string is valid hex, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_hex
@param s a Lua string
@return a boolean value
*/
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);
}
/***
Check if a Lua string is a valid bin-encoded string.
*If the string is valid bin, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_bin
@param s a Lua string
@return a boolean value
*/
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);
}
/***
Check if a Lua string is a valid base32-encoded string.
*If the string is valid base32, it pushes true, otherwise it pushes false onto the Lua stack.
@function OCTET.is_base32
@param s a Lua string
@return a boolean value
*/
static int lua_is_base32(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "string expected");
int len = is_base32(s);
if(!len) {
lua_pushboolean(L, 0);
func(L, "string is not a valid base32 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;
/***
Convert a Lua integer into a 16-byte octet object,
padding the upper 8 bytes with zeros and handling endianness.
@function OCTET.from_number
@param num Lua integer
@return 16-byte octet object
*/
static int from_number(lua_State *L) {
BEGIN();
// number argument, import
int tn;
lua_Integer n = lua_tointegerx(L,1,&tn); SAFE(tn, "Invalid argument, input is not a number");
const uint64_t v = n;
octet *o = o_new(L, 16); SAFE(o, CREATE_OCT_ERR);
// 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_Integer n = lua_tointegerx(L,2,&tn); SAFE(tn, "Invalid argument, len is not a number");
octet *o = o_new(L, (int)n); SAFE(o, CREATE_OCT_ERR);
register int c;
for(c=0;c<n;c++) o->val[c] = s[c];
o->len = (int)n;
END(1);
}
/***
Decode a base64-encoded string into an octet object,
after checking if the input string is valid base64.
@function OCTET.from_base64
@param str base64-encoded string
@return decoded octet object
*/
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); SAFE(len, "Invalid base64 sequence");
int nlen = B64decoded_len(len);
octet *o = o_new(L, nlen); SAFE(o, CREATE_OCT_ERR);
OCT_frombase64(o, (char*)s);
END(1);
}
/***
Decode a url64-encoded string into an octet object,
after checking if the input string is valid url64.
@function OCTET.from_url64
@param str url64-encoded string
@return decoded octet object
*/
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); SAFE(len, "Invalid url64 sequence");
int nlen = B64decoded_len(len);
// func(L,"U64 decode len: %u -> %u",len,nlen);
octet *o = o_new(L, nlen); SAFE(o, CREATE_OCT_ERR);
o->len = U64decode(o->val, (char*)s);
// func(L,"u64 return len: %u",o->len);
END(1);
}
/***
Decode a base58-encoded string into an octet object,
after checking if the input string is valid base58.
@function OCTET.from_base58
@param str base58-encoded string
@return decoded octet object
*/
static int from_base58(lua_State *L) {
BEGIN();
char *failed_msg = NULL;
char *tmp = NULL;
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "base58 string expected");
int len = is_base58(L, s); SAFE(len, "Invalid base58 sequence");
size_t binmax = B64decoded_len(len); //((len + 3) >> 2) *3;
tmp = zmalloc(binmax); SAFE_GOTO(tmp, MALLOC_ERROR);
// size_t binmax = len + len + len;
size_t binlen = binmax;
SAFE(b58tobin((void*)tmp, &binlen, s, len), "Error in conversion from base58");
octet *o = o_new(L, binlen); SAFE_GOTO(o, CREATE_OCT_ERR);
if(binlen>binmax) {
memcpy(o->val,&tmp[binlen-binmax],binmax);
} else {
memcpy(o->val,&tmp[binmax-binlen],binlen);
}
o->len = binlen;
end:
zfree(tmp);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/***
Convert a string into an octet object,
after checking if the input is a valid string.
@function OCTET.from_string
@param str string
@return convert octet object
*/
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); SAFE(len <= MAX_OCTET, "Invalid string size, too long");
octet *o = o_new(L, len+1); SAFE(o, CREATE_OCT_ERR);
register int i = 0;
for(i=0;s[i] != 0x0;i++) o->val[i]=s[i];
o->len = i;
o->val[i] = 0x0;
END(1);
}
/***
Decode an hexadecimal-encoded string into an octet object,
after checking if the input string is valid hexadecimal.
@function OCTET.from_hex
@param str hexadecimal-encoded string
@return decoded octet object
*/
static int from_hex(lua_State *L) {
BEGIN();
char *s = (char*)lua_tostring(L, 1); SAFE(s, "Invalid argument, string exptected");
int len;
if ( (s[0] == '0') && (s[1] == 'x') )
len = is_hex(L, s+2);
else len = is_hex(L, s);
SAFE(len, "Invalid hex sequence");
func(L,"hex string sequence length: %u",len);
SAFE(len <= MAX_FILE<<1, "Invalid hex sequence, too long");
octet *o = o_new(L, len>>1); SAFE(o, CREATE_OCT_ERR);
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);
}
SAFE(o->len >= 0, "Invalid octet in hex string")
END(1);
}
/***
Convert a binary string (composed of '0' and '1' characters) into an octet object.
@function OCTET.from_bin
@param bin binary string
@return convert octet object
*/
// 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); SAFE(len, "Invalid binary sequence");
SAFE(len <= MAX_FILE, "Invalid binary sequence, too long");
octet *o = o_new(L, len+4); SAFE(o, CREATE_OCT_ERR);
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.
@function OCTET.from_segwit
@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); SAFE(s, "Invalid argument, string exptected")
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);
}
SAFE(ret, "Invalid bech32 address");
octet *o = o_new(L, witprog_len); SAFE(o, CREATE_OCT_ERR);
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`.
HRP (human readble part) are the first characters of the address, they can
be bc (bitcoin network) or tb (testnet network).
@function OCTET:to_segwit
@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;
const octet *o = o_arg(L,1); SAFE_GOTO(o, ALLOCATE_OCT_ERR);
if(!o->len) { lua_pushnil(L); goto end; }
int tn;
lua_Integer witver = lua_tointegerx(L, 2, &tn); SAFE_GOTO(tn, "segwit version is not a number");
SAFE_GOTO(witver >= 0 && witver <= 16, "Invalid segwit version, must be between 0 and 16");
const char *s = lua_tostring(L, 3); SAFE_GOTO(s, "Invalid 3rd argument, string expected");
SAFE_GOTO(o->len >= 2 && o->len <= 40, "Invalid segwit address size, must be between 2 and 40");
// 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';
SAFE_GOTO(s[i] == '\0' && (strncmp(hrp, "bc", 2) == 0 || strncmp(hrp, "tb", 2) == 0), "Invalid human readable part");
result = zmalloc(73+strlen(hrp)); SAFE_GOTO(result, MALLOC_ERROR);
SAFE_GOTO(segwit_addr_encode(result, hrp, witver, (uint8_t*)o->val, o->len), "Cannot be encoded to segwit format");
lua_pushstring(L,result);
end:
if(result) zfree(result);
o_free(L, o);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/***
Decode a base45-encoded string into an octet object,
after checking if the input string is valid base45.
@function OCTET.from_base45
@param str base45-encoded string
@return decoded octet object
*/
static int from_base45(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "base45 string expected");
int len = is_base45(s); SAFE(len >= 0, "Invalid base45 sequence");
octet *o = o_new(L, len); SAFE(o, CREATE_OCT_ERR);
len = b45decode(o->val, s); SAFE(len >= 0, "Invalid base45 sequence");
o->len = len;
END(1);
}
/***
Decode a base32-encoded string into an octet object,
after checking if the input string is valid base32.
@function OCTET.from_base32
@param str base32-encoded string
@return decoded octet object
*/
static int from_base32(lua_State *L) {
BEGIN();
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "base32 string expected");
int len_in = is_base32(s); SAFE(len_in, "Invalid base32 sequence");
int max_len_out = len_in * 5 / 8;
octet *o = o_new(L, max_len_out); SAFE(o, CREATE_OCT_ERR);
int decoded_len = b32decode(o->val, s); SAFE(decoded_len >= 0, "Invalid base32 sequence");
o->len = decoded_len;
END(1);
}
/***
Decode a base32 crockford-encoded string into an octet object,
after checking if the input string is valid base32 crockford.
It can also take a second parameter (true) if you want to perform decoding with a checksum.
Additionally, before decoding, it removes the '-' characters.
@function OCTET.from_base32_crockford
@param str base32 crockford-encoded string
@param boolean by default it is set to false
@return decoded octet object
*/
static int from_base32_crockford(lua_State *L) {
BEGIN();
char *failed_msg = NULL;
const char *s_in = lua_tostring(L, 1);
luaL_argcheck(L, s_in != NULL, 1, "base32 string expected");
int use_checksum = lua_toboolean(L, 2);
char *s = zmalloc(strlen(s_in) + 1); SAFE_GOTO(s, MALLOC_ERROR);
int k = 0;
for (int i = 0; s_in[i]; i++) {
if (s_in[i] != '-') s[k++] = s_in[i];
}
s[k] = '\0';
int len_in = is_base32_crockford(s, use_checksum); SAFE_GOTO(len_in, "Invalid Crockford base32 sequence");
int max_len_out = len_in * 5 / 8;
octet *o = o_new(L, max_len_out); SAFE_GOTO(o, CREATE_OCT_ERR);
int decoded_len = b32crockford_decode(o->val, s, use_checksum); SAFE_GOTO(decoded_len, "Crockford base32 decoding failed");
o->len = decoded_len;
end:
if (s) zfree(s);
if(failed_msg) {
THROW(failed_msg);
}
END(1);
}
/***
Decode a mnemonic-encoded string into an octet object,
after checking if the input string is valid mnemonic.
@function OCTET.from_mnemonic
@param str mnemonic-encoded string
@return decoded octet object
*/