-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtela.go
More file actions
2211 lines (1819 loc) · 54.8 KB
/
Copy pathtela.go
File metadata and controls
2211 lines (1819 loc) · 54.8 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
package tela
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/civilware/Gnomon/rwc"
"github.com/civilware/tela/logger"
"github.com/civilware/tela/shards"
"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/channel"
"github.com/deroproject/derohe/cryptography/crypto"
"github.com/deroproject/derohe/dvm"
"github.com/deroproject/derohe/globals"
"github.com/deroproject/derohe/rpc"
"github.com/deroproject/derohe/walletapi"
"github.com/gorilla/websocket"
_ "embed"
)
// TELA-DOC-1 structure
type DOC struct {
DocType string `json:"docType"` // Language this document is using (ex: "TELA-HTML-1", "TELA-JS-1" or "TELA-CSS-1")
Code string `json:"code"` // The application code HTML, JS... (when a DOC is returned this will be the SC code, the DocCode can be retrieved with ExtractDocCode)
SubDir string `json:"subDir"` // Sub directory to place file in (always use / for further children, ex: "sub1" or "sub1/sub2/sub3")
SCID string `json:"scid"` // SCID of this DOC, only used after DOC has been installed on-chain
Author string `json:"author"` // Author of this DOC, only used after DOC has been installed on-chain
DURL string `json:"dURL"` // TELA dURL
Compression string `json:"compression"` // Compression format if used on this DOC (ex: .gz)
SCVersion *Version `json:"version,omitempty"` // Version of this DOC SC
// Signature values of Code
Signature `json:"signature"`
// Standard headers
Headers `json:"headers"`
}
// TELA-INDEX-1 structure
type INDEX struct {
SCID string `json:"scid"` // SCID of this INDEX, only used after INDEX has been installed on-chain
Author string `json:"author"` // Author of this INDEX, only used after INDEX has been installed on-chain
DURL string `json:"dURL"` // TELA dURL
Mods string `json:"mods"` // TELA modules string, stores addition functionality to be parsed when validating, module tags are separated by comma
DOCs []string `json:"docs"` // SCIDs of TELA DOCs embedded in this INDEX SC
SCVersion *Version `json:"version,omitempty"` // Version of this INDEX SC
SC dvm.SmartContract `json:"-"` // DVM smart contract is used for further parsing of installed INDEXs
// Standard headers
Headers `json:"headers"`
}
// Cloning structure for creating DOC/INDEX
type Cloning struct {
BasePath string `json:"basePath"` // Main directory path for TELA files
ServePath string `json:"servePath"` // URL serve path
Entrypoint string `json:"entrypoint"` // INDEX entrypoint
DURL string `json:"dURL"` // TELA dURL
Hash string `json:"hash"` // Commit hash of INDEX
}
// Library structure for search queries
type Library struct {
DURL string `json:"dURL"` // TELA library dURL
Author string `json:"author"` // Author of the library
SCID string `json:"scid"` // SCID of the library DOC or INDEX
LikesRatio float64 `json:"likesRatio"` // Likes to dislike ratio of the library
}
// Local TELA server info
type ServerInfo struct {
Name string
Address string
SCID string
Entrypoint string
}
// Datashards structure
type ds struct {
main string
}
// TELA core components for serving content from TELA-INDEX-1 smart contracts
type TELA struct {
sync.RWMutex
servers map[ServerInfo]*http.Server
path ds // Access datashard paths
updates bool // Allow updated content
port int // Start port to range servers from
max int // Max amount of TELA servers
version struct {
pkg Version
index []Version
docs []Version
}
client struct {
WS *websocket.Conn
RPC *jrpc2.Client
}
}
// Versioning structure used for package and contracts
type Version struct {
Major int `json:"major"`
Minor int `json:"minor"`
Patch int `json:"patch"`
}
var tela TELA
const DOC_STATIC = "TELA-STATIC-1" // Generic docType for any file type
const DOC_HTML = "TELA-HTML-1" // HTML docType
const DOC_JSON = "TELA-JSON-1" // JSON docType
const DOC_CSS = "TELA-CSS-1" // CSS docType
const DOC_JS = "TELA-JS-1" // JavaScript docType
const DOC_MD = "TELA-MD-1" // Markdown docType
const DOC_GO = "TELA-GO-1" // Golang docType
const DEFAULT_MAX_SERVER = 20 // Default max amount of servers
const DEFAULT_PORT_START = 8082 // Default start port for servers
const DEFAULT_MIN_PORT = 1200 // Minimum port of possible serving range
const DEFAULT_MAX_PORT = 65535 // Maximum port of possible serving range
const MINIMUM_GAS_FEE = uint64(100) // Minimum gas fee used when making transfers
const TAG_LIBRARY = ".lib" // A collection of standard DOCs embedded within an INDEX, each DOC is its own file (usage is appended to INDEX and DOC dURLs)
const TAG_DOC_SHARD = ".shard" // A DocShard DOC (usage is appended to DOC dURLs)
const TAG_DOC_SHARDS = ".shards" // A collection of DocShard DOCs embedded within an INDEX, when recreated this will be one file (usage is appended to INDEX dURLs)
const TAG_BOOTSTRAP = ".bootstrap" // A collection of TELA INDEXs or DOCs which can be used to bootstrap a list of applications or content (usage is appended to INDEX dURLs)
// Accepted languages of this TELA package
var acceptedLanguages = []string{DOC_STATIC, DOC_HTML, DOC_JSON, DOC_CSS, DOC_JS, DOC_MD, DOC_GO}
// // Embed the standard TELA smart contracts
//go:embed */TELA-INDEX-1.bas
var TELA_INDEX_1 string
//go:embed */TELA-DOC-1.bas
var TELA_DOC_1 string
// Initialize the default storage path TELA will use, can be changed with SetShardPath if required
func init() {
tela.version.pkg = Version{Major: 1, Minor: 0, Patch: 0}
tela.version.index = []Version{
{Major: 1, Minor: 0, Patch: 0},
{Major: 1, Minor: 1, Patch: 0},
}
tela.version.docs = []Version{
{Major: 1, Minor: 0, Patch: 0},
}
tela.path.main = shards.GetPath()
initMods()
initRatings()
tela.port = DEFAULT_PORT_START
tela.max = DEFAULT_MAX_SERVER
// Cleanup any residual files before package is used
os.RemoveAll(tela.path.tela())
}
// Returns semantic string
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
// LessThan returns true if v is less than ov
func (v *Version) LessThan(ov Version) bool {
if v.Major < ov.Major {
return true
} else if v.Major > ov.Major {
return false
}
if v.Minor < ov.Minor {
return true
} else if v.Minor > ov.Minor {
return false
}
if v.Patch < ov.Patch {
return true
} else if v.Patch > ov.Patch {
return false
}
return false
}
// Equal returns true if v is equal to ov
func (v *Version) Equal(ov Version) bool {
return v.Major == ov.Major && v.Minor == ov.Minor && v.Patch == ov.Patch
}
// Returns TELA datashard path
func (s ds) tela() string {
return filepath.Join(s.main, "tela")
}
// Returns TELA clone path
func (s ds) clone() string {
return filepath.Join(s.main, "clone")
}
// Find if port is within valid range
func isValidPort(port int) bool {
if port < DEFAULT_MIN_PORT || port > DEFAULT_MAX_PORT-tela.max {
return false
}
return true
}
// Listen for open ports and returns http server for TELA content on open port if found
func FindOpenPort() (server *http.Server, found bool) {
max := tela.port + tela.max
port := tela.port // Start on tela.port and try +20
server = &http.Server{Addr: fmt.Sprintf(":%d", port)}
for !found && port < max {
li, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
logger.Debugf("[TELA] Finding port: %s\n", err)
port++ // Not found, try next port
server.Addr = fmt.Sprintf(":%d", port)
time.Sleep(time.Millisecond * 50)
continue
}
li.Close()
found = true
}
if !found {
server = nil
}
return
}
// Check if language used is accepted by TELA, see acceptedLanguages for full list
func IsAcceptedLanguage(language string) bool {
for _, l := range acceptedLanguages {
if language == l {
return true
}
}
return false
}
// Parse a TELA DOC that has been formatted for DocShards and get its code shard
func parseDocShardCode(fileName, code string) (shard []byte, err error) {
start := strings.Index(code, "/*")
end := strings.Index(code, "*/")
if start == -1 || end == -1 {
err = fmt.Errorf("could not parse multiline comment from %s", fileName)
return
}
comment := code[start+3:]
comment = strings.TrimSuffix(comment, "\n*/")
shard = []byte(comment)
return
}
// Parse a TELA DOC for its multiline comment
func parseDocCode(code string) (comment string, err error) {
start := strings.Index(code, "/*")
end := strings.Index(code, "*/")
if start == -1 || end == -1 {
err = fmt.Errorf("could not parse multiline comment")
return
}
comment = code[start+2:]
comment = strings.TrimSpace(strings.TrimSuffix(comment, "*/"))
return
}
// Parse a TELA DOC for useable code and write file if IsAcceptedLanguage
func parseAndSaveTELADoc(filePath, code, doctype, compression string) (err error) {
var comment string
comment, err = parseDocCode(code)
if err != nil {
return
}
// TODO any further DOC parsing for docTypes
switch doctype {
case DOC_HTML:
case DOC_JSON:
case DOC_CSS:
case DOC_JS:
case DOC_MD:
case DOC_GO:
case DOC_STATIC:
default:
err = fmt.Errorf("invalid docType")
return
}
var docCode []byte
docCode, err = Decompress([]byte(comment), compression)
if err != nil {
err = fmt.Errorf("failed to decompress: %s", err)
return
}
err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
if err != nil {
return
}
logger.Printf("[TELA] Creating %s\n", filepath.Base(filePath))
return os.WriteFile(filePath, docCode, 0644)
}
// Decode a hex string if possible otherwise return it
func decodeHexString(hexStr string) string {
if decode, err := hex.DecodeString(hexStr); err == nil {
return string(decode)
}
return hexStr
}
// Handle all the GetSC append errors to result.ValuesString
func getSCErrors(result string) bool {
errStr := []string{
"NOT AVAILABLE err:",
"Unmarshal error",
"UNKNOWN Data type",
}
for _, str := range errStr {
if strings.Contains(result, str) {
return true
}
}
return false
}
// Get a string key from smart contract at endpoint
func getContractVar(scid, key, endpoint string) (variable string, err error) {
var params = rpc.GetSC_Params{SCID: scid, Variables: false, Code: false, KeysString: []string{key}}
var result rpc.GetSC_Result
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
err = tela.client.RPC.CallResult(context.Background(), "DERO.GetSC", params, &result)
if err != nil {
return
}
res := result.ValuesString
if len(res) < 1 || res[0] == "" || getSCErrors(res[0]) {
err = fmt.Errorf("invalid string value for %q", key)
return
}
// uint values don't need to be decoded
if key == "likes" || key == "dislikes" {
variable = res[0]
return
}
variable = decodeHexString(res[0])
return
}
// Get a TXID as hex from daemon endpoint
func getTXID(txid, endpoint string) (txidAsHex string, height int64, err error) {
var params = rpc.GetTransaction_Params{Tx_Hashes: []string{txid}}
var result rpc.GetTransaction_Result
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
err = tela.client.RPC.CallResult(context.Background(), "DERO.GetTransaction", params, &result)
if err != nil {
return
}
res := result.Txs_as_hex
if len(res) < 1 || res[0] == "" {
err = fmt.Errorf("no data found for TXID %s", txid)
return
}
txidAsHex = res[0]
height = result.Txs[0].Block_Height
return
}
// Get the current state of all string keys in a smart contract
func getContractVars(scid, endpoint string) (vars map[string]interface{}, err error) {
var params = rpc.GetSC_Params{SCID: scid, Variables: true, Code: false}
var result rpc.GetSC_Result
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
err = tela.client.RPC.CallResult(context.Background(), "DERO.GetSC", params, &result)
if err != nil {
return
}
vars = result.VariableStringKeys
return
}
// Get the current code of a smart contract at endpoint
func getContractCode(scid, endpoint string) (code string, err error) {
var params = rpc.GetSC_Params{SCID: scid, Variables: false, Code: true}
var result rpc.GetSC_Result
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
err = tela.client.RPC.CallResult(context.Background(), "DERO.GetSC", params, &result)
if err != nil {
return
}
if result.Code == "" {
err = fmt.Errorf("code is empty string")
return
}
code = result.Code
return
}
// Get the code of a smart contract at height from endpoint
func getContractCodeAtHeight(height int64, scid, endpoint string) (code string, err error) {
var params = rpc.GetSC_Params{SCID: scid, Variables: false, Code: true, TopoHeight: height}
var result rpc.GetSC_Result
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
err = tela.client.RPC.CallResult(context.Background(), "DERO.GetSC", params, &result)
if err != nil {
return
}
if result.Code == "" {
err = fmt.Errorf("code is empty string")
return
}
code = result.Code
return
}
// Get a default DERO transfer address for the network defined by globals.Arguments --testnet and --simulator flags
func GetDefaultNetworkAddress() (network, destination string) {
network = "mainnet"
if b, ok := globals.Arguments["--testnet"].(bool); ok && b {
network = "testnet"
if b, ok := globals.Arguments["--simulator"].(bool); ok && b {
network = "simulator"
}
}
switch network {
case "simulator":
destination = "deto1qyvyeyzrcm2fzf6kyq7egkes2ufgny5xn77y6typhfx9s7w3mvyd5qqynr5hx"
case "testnet":
destination = "deto1qy0ehnqjpr0wxqnknyc66du2fsxyktppkr8m8e6jvplp954klfjz2qqdzcd8p"
default:
destination = "dero1qykyta6ntpd27nl0yq4xtzaf4ls6p5e9pqu0k2x4x3pqq5xavjsdxqgny8270"
}
return
}
// Get DERO gas estimate for transfers and args
func GetGasEstimate(wallet *walletapi.Wallet_Disk, ringsize uint64, transfers []rpc.Transfer, args rpc.Arguments) (gasFees uint64, err error) {
if wallet == nil {
err = fmt.Errorf("no wallet for transfer")
return
}
if ringsize < 2 {
ringsize = 2
} else if ringsize > 128 {
ringsize = 128
}
// Initialize a DERO transfer if none is provided
if transfers == nil || len(transfers) < 1 {
_, dest := GetDefaultNetworkAddress()
transfers = []rpc.Transfer{{Destination: dest, Amount: 0}}
}
// Validate all transfer addresses
for i, t := range transfers {
_, err = globals.ParseValidateAddress(t.Destination)
if err != nil {
err = fmt.Errorf("invalid transfer address %d: %s", i, err)
return
}
}
var code string
if c, ok := args.Value(rpc.SCCODE, rpc.DataString).(string); ok {
code = c
}
// Get gas estimate for transfer
gasParams := rpc.GasEstimate_Params{
Transfers: transfers,
SC_Code: code,
SC_Value: 0,
SC_RPC: args,
Ringsize: ringsize,
}
if ringsize == 2 {
gasParams.Signer = wallet.GetAddress().String()
}
endpoint := walletapi.Daemon_Endpoint_Active
tela.client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+endpoint+"/ws", nil)
if err != nil {
err = fmt.Errorf("could not dial daemon endpoint %s: %s", endpoint, err)
return
}
input_output := rwc.New(tela.client.WS)
tela.client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil)
var gasResult rpc.GasEstimate_Result
if err = tela.client.RPC.CallResult(context.Background(), "DERO.GetGasEstimate", gasParams, &gasResult); err != nil {
err = fmt.Errorf("could not estimate fees: %s", err)
return
}
if gasResult.GasStorage < MINIMUM_GAS_FEE {
gasResult.GasStorage = MINIMUM_GAS_FEE
}
gasFees = gasResult.GasStorage
return
}
// transfer0 is used for executing TELA smart contract functions without a DEROVALUE or ASSETVALUE, it creates a transfer of 0 to a default address for the network
func transfer0(wallet *walletapi.Wallet_Disk, ringsize uint64, args rpc.Arguments) (txid string, err error) {
return Transfer(wallet, ringsize, nil, args)
}
// Transfer is used for executing TELA smart contract actions with DERO walletapi, if nil transfers is passed
// it initializes a transfer of 0 to a default address for the network using GetDefaultNetworkAddress()
func Transfer(wallet *walletapi.Wallet_Disk, ringsize uint64, transfers []rpc.Transfer, args rpc.Arguments) (txid string, err error) {
var gasFees uint64
gasFees, err = GetGasEstimate(wallet, ringsize, transfers, args)
if err != nil {
return
}
tx, err := wallet.TransferPayload0(transfers, ringsize, false, args, gasFees, false)
if err != nil {
err = fmt.Errorf("transfer build error: %s", err)
return
}
if err = wallet.SendTransaction(tx); err != nil {
err = fmt.Errorf("transfer dispatch error: %s", err)
return
}
txid = tx.GetHash().String()
return
}
// Clone a TELA-DOC SCID to path from endpoint
func cloneDOC(scid, docNum, path, endpoint string) (clone Cloning, err error) {
if len(scid) != 64 {
err = fmt.Errorf("invalid DOC SCID: %s", scid)
return
}
var code string
code, err = getContractCode(scid, endpoint)
if err != nil {
err = fmt.Errorf("could not get SC code from %s: %s", scid, err)
return
}
_, _, err = ValidDOCVersion(code)
if err != nil {
err = fmt.Errorf("scid does not parse as TELA-DOC-1: %s", err)
return
}
var docType string
docType, err = getContractVar(scid, HEADER_DOCTYPE.Trim(), endpoint)
if err != nil {
err = fmt.Errorf("could not get docType from %s: %s", scid, err)
return
}
var fileName string
fileName, err = getContractVar(scid, HEADER_NAME_V2.Trim(), endpoint)
if err != nil {
fileName, err = getContractVar(scid, HEADER_NAME.Trim(), endpoint)
if err != nil {
err = fmt.Errorf("could not get nameHdr from %s", scid)
return
}
}
var compression string
ext := filepath.Ext(fileName)
if IsCompressedExt(ext) {
compression = ext
}
recreate := strings.TrimSuffix(fileName, compression)
// Set entrypoint DOC
isDOC1 := Header(docNum) == HEADER_DOCUMENT.Number(1)
if isDOC1 {
clone.Entrypoint = recreate
}
// Check if DOC is to be placed in subDir
var subDir string
subDir, err = getContractVar(scid, HEADER_SUBDIR.Trim(), endpoint)
if err != nil && !strings.Contains(err.Error(), "invalid string value for") { // only return on RPC error
err = fmt.Errorf("could not get subDir for %s: %s", fileName, err)
return
}
// If a valid subDir was decoded add it to path for this DOC
if subDir != "" {
// Split all subDir to create path
split := strings.Split(subDir, "/")
for _, s := range split {
path = filepath.Join(path, s)
}
// If serving from subDir point to it
if isDOC1 {
clone.ServePath = fmt.Sprintf("/%s", subDir)
}
}
filePath := filepath.Join(path, recreate)
if _, err = os.Stat(filePath); !os.IsNotExist(err) {
err = fmt.Errorf("file %s already exists", filePath)
return
}
if !IsAcceptedLanguage(docType) {
err = fmt.Errorf("%s is not an accepted language for DOC %s", docType, fileName)
return
}
err = parseAndSaveTELADoc(filePath, code, docType, compression)
if err != nil {
err = fmt.Errorf("error saving %s: %s", fileName, err)
return
}
return
}
// Clone a TELA-INDEX SCID to path from endpoint creating all DOCs embedded within the INDEX
func cloneINDEX(scid, dURL, path, endpoint string) (clone Cloning, err error) {
if len(scid) != 64 {
err = fmt.Errorf("invalid INDEX SCID: %s", scid)
return
}
tagErr := fmt.Sprintf("cloning %s@%s was not successful:", dURL, scid)
hash, err := getContractVar(scid, "hash", endpoint)
if err != nil {
err = fmt.Errorf("%s could not get commit hash: %s", tagErr, err)
return
}
tagCommit := fmt.Sprintf("%s@%s", dURL, hash)
// If the user does not want updated content
if !tela.updates && scid != hash {
err = fmt.Errorf("%s user defined no updates and content has been updated to %s", tagErr, tagCommit)
return
}
code, err := getContractCode(scid, endpoint)
if err != nil {
err = fmt.Errorf("%s could not get SC code: %s", tagErr, err)
return
}
var modTag string // mods store can be empty so don't return error
if storedMods, err := getContractVar(scid, "mods", endpoint); err == nil {
modTag = storedMods
}
// Only clone contracts matching TELA standard
sc, _, err := ValidINDEXVersion(code, modTag)
if err != nil {
err = fmt.Errorf("%s does not parse as TELA-INDEX-1: %s", tagErr, err)
return
}
// TELA-INDEX entrypoint, this will be nameHdr of DOC1
entrypoint := ""
// Path where file will be stored
basePath := filepath.Join(path, dURL)
// Path to entrypoint
servePath := ""
// If INDEX contains DocShards to be constructed
if strings.HasSuffix(dURL, TAG_DOC_SHARDS) {
err = cloneDocShards(sc, basePath, endpoint)
if err != nil {
err = fmt.Errorf("%s %s", tagErr, err)
return
}
} else {
// Parse INDEX SC for valid DOCs
entrypoint, servePath, err = parseAndCloneINDEXForDOCs(sc, 0, basePath, endpoint)
if err != nil {
// If all of the files were not cloned successfully, any residual files are removed if they did not exist already
err = fmt.Errorf("%s %s", tagErr, err)
if !strings.Contains(err.Error(), "already exists") {
os.RemoveAll(basePath)
}
return
}
}
clone.DURL = dURL
clone.BasePath = basePath
clone.ServePath = servePath
clone.Entrypoint = entrypoint
return
}
// cloneDocShards takes a TELA-INDEX SC and parses its DOCs, creating them as DocShards which get recreated as a single file
func cloneDocShards(sc dvm.SmartContract, basePath, endpoint string) (err error) {
docShards, recreate, compression, err := parseDocShards(sc, basePath, endpoint)
if err != nil {
err = fmt.Errorf("could not clone DocShards: %s", err)
return
}
err = ConstructFromShards(docShards, recreate, basePath, compression)
if err != nil {
err = fmt.Errorf("could not construct DocShards: %s", err)
return
}
return
}
// Get the total amount of shards that would be created if data is used to CreateShardFiles
func GetTotalShards(data []byte) (totalShards int, fileSize int64) {
fileSize = int64(len(data))
totalShards = int((fileSize + SHARD_SIZE - 1) / SHARD_SIZE)
return
}
// ConstructFromShards takes DocShards and recreates them as a file at basePath,
// CreateShardFiles can be used to create the shard files formatted for ConstructFromShards
func ConstructFromShards(docShards [][]byte, recreate, basePath, compression string) (err error) {
err = os.MkdirAll(basePath, os.ModePerm)
if err != nil {
return
}
filePath := filepath.Join(basePath, recreate)
if _, err = os.Stat(filePath); !os.IsNotExist(err) {
err = fmt.Errorf("file %s already exists", filePath)
return
}
logger.Printf("[TELA] Constructing %s\n", recreate)
var file *os.File
file, err = os.Create(filePath)
if err != nil {
err = fmt.Errorf("failed to create %s: %s", recreate, err)
return
}
defer file.Close()
if compression != "" {
var buf bytes.Buffer
for i, code := range docShards {
_, err = buf.Write(code)
if err != nil {
err = fmt.Errorf("failed to write compressed shard %d to %s: %s", i+1, recreate, err)
return
}
}
var decompressed []byte
decompressed, err = Decompress(buf.Bytes(), compression)
if err != nil {
err = fmt.Errorf("failed to decompress %s: %s", recreate, err)
return
}
_, err = file.Write(decompressed)
if err != nil {
err = fmt.Errorf("failed to write decompressed shards to %s: %s", recreate, err)
return
}
} else {
for i, code := range docShards {
_, err = file.Write(code)
if err != nil {
err = fmt.Errorf("failed to write shard %d to %s: %s", i+1, recreate, err)
return
}
}
}
return
}
// CreateShardFiles takes a source file and creates DocShard files sized and formatted for installing as TELA DOCs,
// the package uses ConstructFromShards to re-build the DocShards as its original file when cloning,
// output files are formatted as "name-#.ext+compression" in the source file's directory
// if content is nil the filePath will be read and compression will be applied if used, otherwise content will be handled as is
func CreateShardFiles(filePath, compression string, content []byte) (err error) {
fileName := filepath.Base(filePath)
if content == nil {
content, err = os.ReadFile(filePath)
if err != nil {
err = fmt.Errorf("failed to read file: %s", err)
return
}
if compression != "" {
var compressed string
compressed, err = Compress(content, compression)
if err != nil {
err = fmt.Errorf("could not compress %s: %s", fileName, err)
return
}
content = []byte(compressed)
}
}
for _, r := range string(content) {
if r > unicode.MaxASCII {
err = fmt.Errorf("cannot shard file %s: '%c'", fileName, r)
return
}
}
totalShards, fileSize := GetTotalShards(content)
newFileName := func(i int, name, ext, comp string) string {
return fmt.Sprintf("%s-%d%s%s", strings.TrimSuffix(name, ext), i, ext, comp)
}
fileDir := filepath.Dir(filePath)
ext := filepath.Ext(fileName)
// Check no shard files already exist
for i := 1; i <= totalShards; i++ {
name := newFileName(int(i), fileName, ext, compression)
newPath := filepath.Join(fileDir, name)
if _, err = os.Stat(newPath); !os.IsNotExist(err) {
err = fmt.Errorf("file %s already exists", newPath)
return
}
}
count := 0
for start := int64(0); start < fileSize; start += SHARD_SIZE {
end := start + SHARD_SIZE
if end > fileSize {
end = fileSize
}
count++
name := newFileName(count, fileName, ext, compression)
var shardFile *os.File
shardFile, err = os.Create(filepath.Join(fileDir, name))
if err != nil {
err = fmt.Errorf("failed to create %s: %s", name, err)
return
}
defer shardFile.Close()
if _, err = shardFile.Write(content[start:end]); err != nil {
err = fmt.Errorf("failed to write %s: %s", name, err)
return
}
}
return
}
// Clone a TELA-INDEX SCID at commit TXID to path from endpoint creating all DOCs embedded within the INDEX at the commit height
func cloneINDEXAtCommit(height int64, scid, txid, path, endpoint string) (clone Cloning, err error) {
if len(scid) != 64 {
err = fmt.Errorf("invalid INDEX SCID: %s", scid)
return
}
// TXID only needed on first INDEX
if height == 0 && len(txid) != 64 {
err = fmt.Errorf("invalid INDEX commit TXID: %s", txid)
return
}
dURL, err := getContractVar(scid, HEADER_DURL.Trim(), endpoint)
if err != nil {
err = fmt.Errorf("could not get dURL from %s: %s", scid, err)
return
}
tagErr := fmt.Sprintf("cloning %s@%s was not successful:", dURL, txid)
var code, modTag string
if height > 0 {
// If more then one INDEX embed, use height from commit TXID to get docCode at commit height
code, err = getContractCodeAtHeight(height, scid, endpoint)
if err != nil {
return
}