saito-js 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ name: publish
2
+
3
+ on:
4
+ push:
5
+ branches: [ prod, master ]
6
+ pull_request:
7
+ branches: [ develop, master ]
8
+
9
+ jobs:
10
+ publish:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - name: checkout repo
14
+ uses: actions/Checkout@v3
15
+
16
+ - name: setup node
17
+ uses: actions/setup-node@v3
18
+ with:
19
+ node-version: '16.x'
20
+ registry-url: 'https://registry.npmjs.org'
21
+ cache: npm
22
+ # cache-dependency-path: saito-wasm/package-lock.json
23
+
24
+ - name: get latest version
25
+ run: |
26
+ echo latest_version=$(npm show saito-js version) >> $GITHUB_ENV
27
+ echo current_version=$(npm pkg get version) >> $GITHUB_ENV
28
+ # working-directory: saito-wasm
29
+ - name: version check
30
+ if: ${{ env.latest_version == env.current_version }}
31
+ run: |
32
+ echo "same version is already published"
33
+ echo "current version : ${{ env.current_version }}"
34
+ echo "published version : ${{ env.latest_version }}"
35
+
36
+ - name: Install npm packages
37
+ if: ${{ env.latest_version != env.current_version }}
38
+ run: npm ci
39
+ # working-directory: saito-wasm
40
+
41
+ - name: Publish package
42
+ if: ${{ env.latest_version != env.current_version }}
43
+ run: npm publish
44
+ env:
45
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
46
+ # working-directory: saito-wasm
@@ -0,0 +1,3 @@
1
+ {
2
+ "printWidth": 100
3
+ }
package/index.node.ts CHANGED
@@ -1,4 +1,4 @@
1
- import Saito from './saito';
1
+ import Saito from "./saito";
2
2
  import SharedMethods from "./shared_methods";
3
3
  import Configs from "./configs";
4
4
  import Transaction from "./lib/transaction";
@@ -6,35 +6,46 @@ import Slip from "./lib/slip";
6
6
  import Block from "./lib/block";
7
7
  import Peer from "./lib/peer";
8
8
  import Factory from "./lib/factory";
9
+ import Wallet from "./lib/wallet";
10
+ import Blockchain from "./lib/blockchain";
9
11
 
10
- let cr = require('crypto');
11
- globalThis.crypto = cr.webcrypto;
12
-
12
+ const NODE_MAJOR_VERSION = parseInt(process.versions.node.split(".")[0]);
13
+ if (NODE_MAJOR_VERSION < 20) {
14
+ let cr = require("crypto");
15
+ globalThis.crypto = cr.webcrypto;
16
+ }
13
17
 
14
18
  /**
15
19
  *
16
20
  * @param configs
17
21
  * @param sharedMethods
18
22
  */
19
- export async function initialize(configs: Configs, sharedMethods: SharedMethods, factory: Factory) {
20
- if (Saito.getLibInstance()) {
21
- console.error("saito already initialized");
22
- return;
23
- }
24
- console.log("initializing saito-js");
25
- let saito = await import("saito-wasm/dist/server");
26
- console.log("wasm lib loaded");
27
-
28
- let s = await saito.default;
29
-
30
- Saito.setLibInstance(s);
31
-
32
- Transaction.Type = s.WasmTransaction;
33
- Slip.Type = s.WasmSlip;
34
- Block.Type = s.WasmBlock;
35
- Peer.Type = s.WasmPeer;
36
-
37
- return Saito.initialize(configs, sharedMethods, factory);
23
+ export async function initialize(
24
+ configs: Configs,
25
+ sharedMethods: SharedMethods,
26
+ factory: Factory,
27
+ privateKey: string
28
+ ) {
29
+ if (Saito.getLibInstance()) {
30
+ console.error("saito already initialized");
31
+ return;
32
+ }
33
+ console.log("initializing saito-js");
34
+ let saito = await import("saito-wasm/dist/server");
35
+ console.log("wasm lib loaded");
36
+
37
+ let s = await saito.default;
38
+
39
+ Saito.setLibInstance(s);
40
+
41
+ Transaction.Type = s.WasmTransaction;
42
+ Slip.Type = s.WasmSlip;
43
+ Block.Type = s.WasmBlock;
44
+ Peer.Type = s.WasmPeer;
45
+ Wallet.Type = s.WasmWallet;
46
+ Blockchain.Type = s.WasmBlockchain;
47
+
48
+ return Saito.initialize(configs, sharedMethods, factory, privateKey);
38
49
  }
39
50
 
40
51
  export default Saito;
package/index.web.ts CHANGED
@@ -1,4 +1,4 @@
1
- import Saito from './saito';
1
+ import Saito from "./saito";
2
2
  import SharedMethods from "./shared_methods";
3
3
  import Configs from "./configs";
4
4
  import Transaction from "./lib/transaction";
@@ -6,36 +6,42 @@ import Slip from "./lib/slip";
6
6
  import Block from "./lib/block";
7
7
  import Peer from "./lib/peer";
8
8
  import Factory from "./lib/factory";
9
+ import Wallet from "./lib/wallet";
10
+ import Blockchain from "./lib/blockchain";
9
11
 
10
12
  /**
11
13
  *
12
14
  * @param configs
13
15
  * @param sharedMethods
14
16
  */
15
- export async function initialize(configs: Configs, sharedMethods: SharedMethods, factory: Factory) {
16
- if (Saito.getLibInstance()) {
17
- console.error("saito already initialized");
18
- return;
19
- }
20
- console.log("initializing saito-js");
17
+ export async function initialize(
18
+ configs: Configs,
19
+ sharedMethods: SharedMethods,
20
+ factory: Factory,
21
+ privateKey: string
22
+ ) {
23
+ if (Saito.getLibInstance()) {
24
+ console.error("saito already initialized");
25
+ return;
26
+ }
27
+ console.log("initializing saito-js");
21
28
 
22
- return import("saito-wasm/dist/browser")
23
- .then((s: any) => {
24
- return s.default;
25
- })
26
- .then((s) => {
27
- Saito.setLibInstance(s);
28
- return s.default()
29
- .then(() => {
30
-
31
- Transaction.Type = s.WasmTransaction;
32
- Slip.Type = s.WasmSlip;
33
- Block.Type = s.WasmBlock;
34
- Peer.Type = s.WasmPeer;
35
- return Saito.initialize(configs, sharedMethods, factory);
36
- });
37
- });
29
+ return import("saito-wasm/dist/browser")
30
+ .then((s: any) => {
31
+ return s.default;
32
+ })
33
+ .then((s) => {
34
+ Saito.setLibInstance(s);
35
+ return s.default().then(() => {
36
+ Transaction.Type = s.WasmTransaction;
37
+ Slip.Type = s.WasmSlip;
38
+ Block.Type = s.WasmBlock;
39
+ Peer.Type = s.WasmPeer;
40
+ Wallet.Type = s.WasmWallet;
41
+ Blockchain.Type = s.WasmBlockchain;
42
+ return Saito.initialize(configs, sharedMethods, factory, privateKey);
43
+ });
44
+ });
38
45
  }
39
46
 
40
-
41
47
  export default Saito;
@@ -0,0 +1,14 @@
1
+ import type {WasmBlockchain} from "saito-wasm/dist/types/pkg/node/index_bg";
2
+
3
+ export default class Blockchain {
4
+ protected blockchain: WasmBlockchain;
5
+ public static Type: any;
6
+
7
+ constructor(blockchain: WasmBlockchain) {
8
+ this.blockchain = blockchain;
9
+ }
10
+
11
+ public async reset() {
12
+ return this.blockchain.reset();
13
+ }
14
+ }
@@ -0,0 +1,92 @@
1
+ import SharedMethods from "../../shared_methods";
2
+ import Saito from "../../saito";
3
+ import Wallet from "../wallet";
4
+ import Blockchain from "../blockchain";
5
+
6
+ export default class CustomSharedMethods implements SharedMethods {
7
+ processApiCall(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): Promise<void> {
8
+ throw new Error("Method not implemented.");
9
+ }
10
+
11
+ connectToPeer(peerData: any): void {
12
+ throw new Error("Method not implemented.");
13
+ }
14
+
15
+ disconnectFromPeer(peerIndex: bigint): void {
16
+ throw new Error("Method not implemented.");
17
+ }
18
+
19
+ fetchBlockFromPeer(url: string): Promise<Uint8Array> {
20
+ throw new Error("Method not implemented.");
21
+ }
22
+
23
+ isExistingFile(key: string): boolean {
24
+ throw new Error("Method not implemented.");
25
+ }
26
+
27
+ loadBlockFileList(): Array<string> {
28
+ throw new Error("Method not implemented.");
29
+ }
30
+
31
+ processApiError(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): void {
32
+ let promise = Saito.getInstance().promises.get(msgIndex);
33
+ if (promise) {
34
+ promise.reject(buffer);
35
+ } else {
36
+ console.error(
37
+ "callback not found for callback index : " + msgIndex + " from peer : " + peerIndex
38
+ );
39
+ }
40
+ }
41
+
42
+ processApiSuccess(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): void {
43
+ let promise = Saito.getInstance().promises.get(msgIndex);
44
+ if (promise) {
45
+ promise.resolve(buffer);
46
+ } else {
47
+ console.error(
48
+ "callback not found for callback index : " + msgIndex + " from peer : " + peerIndex
49
+ );
50
+ }
51
+ }
52
+
53
+ readValue(key: string): Uint8Array | null {
54
+ throw new Error("Method not implemented.");
55
+ }
56
+
57
+ removeValue(key: string): void {
58
+ throw new Error("Method not implemented.");
59
+ }
60
+
61
+ sendMessage(peerIndex: bigint, buffer: Uint8Array): void {
62
+ throw new Error("Method not implemented.");
63
+ }
64
+
65
+ sendMessageToAll(buffer: Uint8Array, exceptions: Array<bigint>): void {
66
+ throw new Error("Method not implemented.");
67
+ }
68
+
69
+ writeValue(key: string, value: Uint8Array): void {
70
+ throw new Error("Method not implemented.");
71
+ }
72
+
73
+ sendInterfaceEvent(event: String, peerIndex: bigint): void {
74
+ throw new Error("Method not implemented.");
75
+ }
76
+
77
+ saveWallet(): void {
78
+ throw new Error("Method not implemented.");
79
+ }
80
+
81
+ loadWallet(): void {
82
+ throw new Error("Method not implemented.");
83
+ }
84
+
85
+ saveBlockchain(): void {
86
+ throw new Error("Method not implemented.");
87
+ }
88
+
89
+ loadBlockchain(): void {
90
+ throw new Error("Method not implemented.");
91
+ }
92
+ }
@@ -1,5 +1,6 @@
1
1
  import Saito from "../../saito";
2
- import CustomSharedMethods from "./shared_methods.custom";
2
+
3
+ import CustomSharedMethods from "./custom_shared_methods";
3
4
 
4
5
  export default class WebSharedMethods extends CustomSharedMethods {
5
6
  connectToPeer(peerData: any): void {
package/lib/factory.ts CHANGED
@@ -2,24 +2,31 @@ import Block from "./block";
2
2
  import Transaction from "./transaction";
3
3
  import Slip from "./slip";
4
4
  import Peer from "./peer";
5
+ import Wallet from "./wallet";
6
+ import Blockchain from "./blockchain";
5
7
 
6
8
  export default class Factory {
7
- constructor() {
8
- }
9
+ constructor() {}
9
10
 
10
- public createBlock(data?: any): Block {
11
- return new Block(data);
12
- }
11
+ public createBlock(data?: any): Block {
12
+ return new Block(data);
13
+ }
13
14
 
14
- public createTransaction<T extends Transaction>(data?: any): Transaction {
15
- return new Transaction(data);
16
- }
15
+ public createTransaction<T extends Transaction>(data?: any): Transaction {
16
+ return new Transaction(data);
17
+ }
17
18
 
18
- public createSlip(data?: any): Slip {
19
- return new Slip(data);
20
- }
19
+ public createSlip(data?: any): Slip {
20
+ return new Slip(data);
21
+ }
21
22
 
22
- public createPeer(data?: any): Peer {
23
- return new Peer(data);
24
- }
23
+ public createPeer(data?: any): Peer {
24
+ return new Peer(data);
25
+ }
26
+ public createWallet(data: any): Wallet {
27
+ return new Wallet(data);
28
+ }
29
+ public createBlockchain(data: any): Blockchain {
30
+ return new Blockchain(data);
31
+ }
25
32
  }
package/lib/slip.ts CHANGED
@@ -49,8 +49,8 @@ export default class Slip {
49
49
  return this.slip.amount;
50
50
  }
51
51
 
52
- public set amount(amount: bigint) {
53
- this.slip.amount = amount;
52
+ public set amount(amount: bigint | number) {
53
+ this.slip.amount = BigInt(amount);
54
54
  }
55
55
 
56
56
  public get publicKey(): string {
@@ -1,4 +1,4 @@
1
- import type {WasmTransaction} from 'saito-wasm/dist/types/pkg/node/index_bg';
1
+ import type {WasmTransaction} from "saito-wasm/dist/types/pkg/node/index_bg";
2
2
  import Slip from "./slip";
3
3
  import Saito from "../saito";
4
4
  import Factory from "./factory";
@@ -56,13 +56,13 @@ export default class Transaction {
56
56
  }
57
57
 
58
58
  public get to(): Array<Slip> {
59
- return this.tx.to.map(slip => {
59
+ return this.tx.to.map((slip) => {
60
60
  return Saito.getInstance().factory.createSlip(slip);
61
61
  });
62
62
  }
63
63
 
64
64
  public get from(): Array<Slip> {
65
- return this.tx.from.map(slip => {
65
+ return this.tx.from.map((slip) => {
66
66
  return Saito.getInstance().factory.createSlip(slip);
67
67
  });
68
68
  }
@@ -111,8 +111,12 @@ export default class Transaction {
111
111
  return this.tx.total_fees;
112
112
  }
113
113
 
114
- public sign() {
115
- Saito.getInstance().signTransaction(this);
114
+ public async sign() {
115
+ return this.tx.sign();
116
+ }
117
+
118
+ public async signAndEncrypt() {
119
+ return this.tx.sign_and_encrypt();
116
120
  }
117
121
 
118
122
  public isFrom(key: string): boolean {
@@ -138,10 +142,8 @@ export default class Transaction {
138
142
  }
139
143
 
140
144
  public static deserialize(buffer: Uint8Array, factory: Factory): Transaction | null {
141
- console.log("1111");
142
145
  try {
143
146
  let wasmTx = Transaction.Type.deserialize(buffer);
144
- console.log("2222");
145
147
  return factory.createTransaction(wasmTx);
146
148
  } catch (e) {
147
149
  console.debug(e);
@@ -149,6 +151,10 @@ export default class Transaction {
149
151
  }
150
152
  }
151
153
 
154
+ public serialize(): Uint8Array {
155
+ return this.tx.serialize();
156
+ }
157
+
152
158
  public packData() {
153
159
  if (Object.keys(this.msg).length === 0) {
154
160
  this.data = new Uint8Array(Buffer.alloc(0));
package/lib/wallet.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { WasmWallet } from "saito-wasm/dist/types/pkg/node/index_bg";
2
+ import Saito from "../saito";
3
+
4
+ export const DefaultEmptyPrivateKey =
5
+ "0000000000000000000000000000000000000000000000000000000000000000";
6
+ export const DefaultEmptyPublicKey =
7
+ "000000000000000000000000000000000000000000000000000000000000000000";
8
+
9
+ export default class Wallet {
10
+ protected wallet: WasmWallet;
11
+ public static Type: any;
12
+
13
+ constructor(wallet: WasmWallet) {
14
+ this.wallet = wallet;
15
+ }
16
+
17
+ public async save() {
18
+ return this.wallet.save();
19
+ }
20
+
21
+ public async load() {
22
+ return this.wallet.load();
23
+ }
24
+
25
+ public async reset() {
26
+ return this.wallet.reset();
27
+ }
28
+
29
+ public async getPublicKey() {
30
+ let key = await this.wallet.get_public_key();
31
+ return key === DefaultEmptyPublicKey ? "" : key;
32
+ }
33
+
34
+ public async setPublicKey(key: string) {
35
+ if (key === "") {
36
+ key = DefaultEmptyPublicKey;
37
+ }
38
+ return this.wallet.set_public_key(key);
39
+ }
40
+
41
+ public async getPrivateKey() {
42
+ let key = await this.wallet.get_private_key();
43
+ return key === DefaultEmptyPrivateKey ? "" : key;
44
+ }
45
+
46
+ public async setPrivateKey(key: string) {
47
+ if (key === "") {
48
+ key = DefaultEmptyPrivateKey;
49
+ }
50
+ return this.wallet.set_private_key(key);
51
+ }
52
+
53
+ public async getBalance() {
54
+ return this.wallet.get_balance();
55
+ }
56
+
57
+ public async getPendingTxs() {
58
+ let txs = await this.wallet.get_pending_txs();
59
+ return txs.map((tx: any) => Saito.getInstance().factory.createTransaction(tx));
60
+ }
61
+ }
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "saito-js",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "js wrappings around saito-core using wasm",
5
5
  "scripts": {
6
6
  "test": "env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha --require ts-node/register 'tests/**/*.ts'",
7
+ "build prod": "webpack --config webpack.prod.config.js",
7
8
  "build": "webpack",
8
9
  "serve": "webpack-dev-server"
9
10
  },
@@ -23,6 +24,7 @@
23
24
  "html-webpack-plugin": "^5.5.0",
24
25
  "ignore-loader": "^0.1.2",
25
26
  "path-browserify": "^1.0.1",
27
+ "prettier": "^2.8.8",
26
28
  "source-map-loader": "^3.0.0",
27
29
  "stream-browserify": "^3.0.0",
28
30
  "ts-loader": "^9.4.2",
@@ -35,6 +37,7 @@
35
37
  "dependencies": {
36
38
  "buffer": "^6.0.3",
37
39
  "cookie-parser": "~1.4.6",
40
+ "saito-wasm": "^0.0.3",
38
41
  "cors": "^2.8.5",
39
42
  "debug": "~4.3.4",
40
43
  "express": "~4.18.2",
package/saito.ts CHANGED
@@ -3,6 +3,8 @@ import Transaction from "./lib/transaction";
3
3
  import Block from "./lib/block";
4
4
  import Factory from "./lib/factory";
5
5
  import Peer from "./lib/peer";
6
+ import Wallet, {DefaultEmptyPrivateKey} from "./lib/wallet";
7
+ import Blockchain from "./lib/blockchain";
6
8
 
7
9
  // export enum MessageType {
8
10
  // HandshakeChallenge = 1,
@@ -31,9 +33,15 @@ export default class Saito {
31
33
  factory = new Factory();
32
34
  promises = new Map<number, any>();
33
35
  private callbackIndex: number = 1;
34
-
35
-
36
- public static async initialize(configs: any, sharedMethods: SharedMethods, factory = new Factory()) {
36
+ private wallet: Wallet | null = null;
37
+ private blockchain: Blockchain | null = null;
38
+
39
+ public static async initialize(
40
+ configs: any,
41
+ sharedMethods: SharedMethods,
42
+ factory = new Factory(),
43
+ privateKey: string
44
+ ) {
37
45
  this.instance = new Saito(factory);
38
46
 
39
47
  // @ts-ignore
@@ -69,11 +77,10 @@ export default class Saito {
69
77
  console.log("fetching block : " + url);
70
78
  sharedMethods.fetchBlockFromPeer(url).then((buffer: Uint8Array) => {
71
79
  Saito.getLibInstance().process_fetched_block(buffer, hash, peer_index);
72
- })
80
+ });
73
81
  },
74
82
  process_api_call: (buffer: Uint8Array, msgIndex: number, peerIndex: bigint) => {
75
83
  return sharedMethods.processApiCall(buffer, msgIndex, peerIndex).then(() => {
76
-
77
84
  });
78
85
  },
79
86
  process_api_success: (buffer: Uint8Array, msgIndex: number, peerIndex: bigint) => {
@@ -84,10 +91,24 @@ export default class Saito {
84
91
  },
85
92
  send_interface_event: (event: string, peerIndex: bigint) => {
86
93
  return sharedMethods.sendInterfaceEvent(event, peerIndex);
87
- }
94
+ },
95
+ save_wallet: (wallet: any) => {
96
+ return sharedMethods.saveWallet(wallet);
97
+ },
98
+ load_wallet: (wallet: any) => {
99
+ return sharedMethods.loadWallet(wallet);
100
+ },
101
+ save_blockchain: (blockchain: any) => {
102
+ return sharedMethods.saveBlockchain(blockchain);
103
+ },
104
+ load_blockchain: (blockchain: any) => {
105
+ return sharedMethods.loadBlockchain(blockchain);
106
+ },
88
107
  };
89
-
90
- await Saito.getLibInstance().initialize(JSON.stringify(configs));
108
+ if (privateKey === "") {
109
+ privateKey = DefaultEmptyPrivateKey;
110
+ }
111
+ await Saito.getLibInstance().initialize(JSON.stringify(configs), privateKey);
91
112
 
92
113
  console.log("saito initialized");
93
114
 
@@ -142,13 +163,13 @@ export default class Saito {
142
163
  return Saito.getInstance().factory.createBlock(block) as B;
143
164
  }
144
165
 
145
- public async getPublicKey(): Promise<string> {
146
- return Saito.getLibInstance().get_public_key();
147
- }
148
-
149
- public async getPrivateKey(): Promise<string> {
150
- return Saito.getLibInstance().get_private_key();
151
- }
166
+ // public async getPublicKey(): Promise<string> {
167
+ // return Saito.getLibInstance().get_public_key();
168
+ // }
169
+ //
170
+ // public async getPrivateKey(): Promise<string> {
171
+ // return Saito.getLibInstance().get_private_key();
172
+ // }
152
173
 
153
174
  public async processNewPeer(index: bigint, peer_config: any): Promise<void> {
154
175
  return Saito.getLibInstance().process_new_peer(index, peer_config);
@@ -162,7 +183,11 @@ export default class Saito {
162
183
  return Saito.getLibInstance().process_msg_buffer_from_peer(buffer, peer_index);
163
184
  }
164
185
 
165
- public async processFetchedBlock(buffer: Uint8Array, hash: Uint8Array, peer_index: bigint): Promise<void> {
186
+ public async processFetchedBlock(
187
+ buffer: Uint8Array,
188
+ hash: Uint8Array,
189
+ peer_index: bigint
190
+ ): Promise<void> {
166
191
  return Saito.getLibInstance().process_fetched_block(buffer, hash, peer_index);
167
192
  }
168
193
 
@@ -188,31 +213,35 @@ export default class Saito {
188
213
  fee = BigInt(0),
189
214
  force_merge = false
190
215
  ): Promise<T> {
191
- let wasmTx = await Saito.getLibInstance().create_transaction(publickey, amount, fee, force_merge);
216
+ let wasmTx = await Saito.getLibInstance().create_transaction(
217
+ publickey,
218
+ amount,
219
+ fee,
220
+ force_merge
221
+ );
192
222
  let tx = Saito.getInstance().factory.createTransaction(wasmTx) as T;
193
223
  tx.timestamp = new Date().getTime();
194
- console.log("wwwwwwwwwww : " + tx.timestamp);
195
224
  return tx;
196
225
  }
197
226
 
198
- public async signTransaction(tx: Transaction): Promise<Transaction> {
199
- tx.packData();
200
- await tx.wasmTransaction.sign();
201
- return tx;
202
- }
227
+ // public async signTransaction(tx: Transaction): Promise<Transaction> {
228
+ // tx.packData();
229
+ // await tx.wasmTransaction.sign();
230
+ // return tx;
231
+ // }
203
232
 
204
- public async getPendingTransactions<Tx extends Transaction>(): Promise<Array<Tx>> {
205
- let txs = await Saito.getLibInstance().get_pending_txs();
206
- return txs.map((tx: any) => Saito.getInstance().factory.createTransaction(tx));
207
- }
233
+ // public async getPendingTransactions<Tx extends Transaction>(): Promise<Array<Tx>> {
234
+ // let txs = await Saito.getLibInstance().get_pending_txs();
235
+ // return txs.map((tx: any) => Saito.getInstance().factory.createTransaction(tx));
236
+ // }
208
237
 
209
- public async signAndEncryptTransaction(tx: Transaction) {
210
- return tx.wasmTransaction.sign_and_encrypt();
211
- }
238
+ // public async signAndEncryptTransaction(tx: Transaction) {
239
+ // return tx.wasmTransaction.sign_and_encrypt();
240
+ // }
212
241
 
213
- public async getBalance(): Promise<bigint> {
214
- return Saito.getLibInstance().get_balance();
215
- }
242
+ // public async getBalance(): Promise<bigint> {
243
+ // return Saito.getLibInstance().get_balance();
244
+ // }
216
245
 
217
246
  public async getPeers(): Promise<Array<Peer>> {
218
247
  let peers = await Saito.getLibInstance().get_peers();
@@ -221,7 +250,6 @@ export default class Saito {
221
250
  });
222
251
  }
223
252
 
224
-
225
253
  public async getPeer(index: bigint): Promise<Peer | null> {
226
254
  let peer = await Saito.getLibInstance().get_peer(index);
227
255
  if (!peer) {
@@ -242,14 +270,18 @@ export default class Saito {
242
270
  return Saito.getLibInstance().propagate_transaction(tx.wasmTransaction);
243
271
  }
244
272
 
245
- public async sendApiCall(buffer: Uint8Array, peerIndex: bigint, waitForReply: boolean): Promise<Uint8Array> {
273
+ public async sendApiCall(
274
+ buffer: Uint8Array,
275
+ peerIndex: bigint,
276
+ waitForReply: boolean
277
+ ): Promise<Uint8Array> {
246
278
  console.log("saito.sendApiCall : peer = " + peerIndex + " wait for reply = " + waitForReply);
247
279
  let callbackIndex = this.callbackIndex++;
248
280
  if (waitForReply) {
249
281
  return new Promise((resolve, reject) => {
250
282
  this.promises.set(callbackIndex, {
251
283
  resolve,
252
- reject
284
+ reject,
253
285
  });
254
286
  Saito.getLibInstance().send_api_call(buffer, callbackIndex, peerIndex);
255
287
  });
@@ -266,12 +298,25 @@ export default class Saito {
266
298
  await Saito.getLibInstance().send_api_error(buffer, msgId, peerIndex);
267
299
  }
268
300
 
269
- public async sendTransactionWithCallback(transaction: Transaction, callback?: any, peerIndex?: bigint): Promise<any> {
301
+ public async sendTransactionWithCallback(
302
+ transaction: Transaction,
303
+ callback?: any,
304
+ peerIndex?: bigint
305
+ ): Promise<any> {
270
306
  // TODO : implement retry on fail
271
307
  // TODO : stun code goes here probably???
272
- console.log("saito.sendTransactionWithCallback : peer = " + peerIndex + " sig = " + transaction.signature);
308
+ console.log(
309
+ "saito.sendTransactionWithCallback : peer = " + peerIndex + " sig = " + transaction.signature
310
+ );
273
311
  let buffer = transaction.wasmTransaction.serialize();
274
- console.log("sendTransactionWithCallback : " + peerIndex + " with length : " + buffer.byteLength + " sent : ", transaction.msg);
312
+ console.log(
313
+ "sendTransactionWithCallback : " +
314
+ peerIndex +
315
+ " with length : " +
316
+ buffer.byteLength +
317
+ " sent : ",
318
+ transaction.msg
319
+ );
275
320
  await this.sendApiCall(buffer, peerIndex || BigInt(0), !!callback)
276
321
  .then((buffer: Uint8Array) => {
277
322
  if (callback) {
@@ -300,23 +345,60 @@ export default class Saito {
300
345
  }
301
346
 
302
347
  public async propagateServices(peerIndex: bigint, services: string[]) {
303
- return Saito.getLibInstance().propagateServices(peerIndex, services);
348
+ return Saito.getLibInstance().propagate_services(peerIndex, services);
304
349
  }
305
350
 
306
- public async sendRequest(message: string, data: any = "", callback?: any, peerIndex?: bigint): Promise<any> {
351
+ public async sendRequest(
352
+ message: string,
353
+ data: any = "",
354
+ callback?: any,
355
+ peerIndex?: bigint
356
+ ): Promise<any> {
307
357
  console.log("saito.sendRequest : peer = " + peerIndex);
308
- let publicKey = await this.getPublicKey();
358
+ let wallet = await this.getWallet();
359
+ let publicKey = await wallet.getPublicKey();
309
360
  let tx = await this.createTransaction(publicKey, BigInt(0), BigInt(0));
310
361
  tx.msg = {
311
362
  request: message,
312
363
  data: data,
313
364
  };
314
365
  tx.packData();
315
- return this.sendTransactionWithCallback(tx, (tx: Transaction) => {
316
- if (callback) {
317
- return callback(tx.msg);
318
- }
319
- }, peerIndex);
366
+ return this.sendTransactionWithCallback(
367
+ tx,
368
+ (tx: Transaction) => {
369
+ if (callback) {
370
+ return callback(tx.msg);
371
+ }
372
+ },
373
+ peerIndex
374
+ );
320
375
  }
321
- }
322
376
 
377
+ public async getWallet() {
378
+ if (!this.wallet) {
379
+ let w = await Saito.getLibInstance().get_wallet();
380
+ this.wallet = this.factory.createWallet(w);
381
+ }
382
+ return this.wallet;
383
+ }
384
+
385
+ public async getBlockchain() {
386
+ if (!this.blockchain) {
387
+ let b = await Saito.getLibInstance().get_blockchain();
388
+ this.blockchain = this.factory.createBlockchain(b);
389
+ }
390
+ return this.blockchain;
391
+ }
392
+
393
+ // public async loadWallet() {
394
+ // return Saito.getLibInstance().load_wallet();
395
+ // }
396
+ //
397
+ // public async saveWallet() {
398
+ // return Saito.getLibInstance().save_wallet();
399
+ // }
400
+ //
401
+ // public async resetWallet() {
402
+ // return Saito.getLibInstance().reset_wallet();
403
+ // }
404
+ }
package/shared_methods.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import Wallet from "./lib/wallet";
2
+ import Blockchain from "./lib/blockchain";
3
+
1
4
  export default interface SharedMethods {
2
5
  sendMessage(peerIndex: bigint, buffer: Uint8Array): void;
3
6
 
@@ -27,4 +30,11 @@ export default interface SharedMethods {
27
30
 
28
31
  sendInterfaceEvent(event: String, peerIndex: bigint): void;
29
32
 
33
+ saveWallet(wallet: Wallet): void;
34
+
35
+ loadWallet(wallet: Wallet): void;
36
+
37
+ saveBlockchain(blockchain: Blockchain): void;
38
+
39
+ loadBlockchain(blockchain: Blockchain): void;
30
40
  }
@@ -0,0 +1,136 @@
1
+ const path = require('path');
2
+ const webpack = require('webpack');
3
+ const {merge} = require("webpack-merge");
4
+
5
+ let config = {
6
+ optimization: {
7
+ minimize: true,
8
+ },
9
+ // Path to your entry point. From this file Webpack will begin his work
10
+ // entry: ["babel-polyfill", path.resolve(__dirname, entrypoint)],
11
+ resolve: {
12
+ // Add '.ts' and '.tsx' as resolvable extensions.
13
+ extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".wasm", "..."],
14
+ fallback: {
15
+ "fs": false,
16
+ "tls": false,
17
+ "net": false,
18
+ "path": require.resolve("path-browserify"),
19
+ "zlib": false,
20
+ "http": false,
21
+ "https": false,
22
+ "stream": require.resolve("stream-browserify"),
23
+ "buffer": require.resolve("buffer"),
24
+ "crypto": require.resolve("crypto-browserify"),
25
+ "crypto-browserify": require.resolve("crypto-browserify"),
26
+ "async_hooks": false,
27
+ 'process/browser': require.resolve('process/browser'),
28
+ "util": require.resolve("util/"),
29
+ "url": require.resolve("url/")
30
+ }
31
+ },
32
+ module: {
33
+ rules: [
34
+ // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
35
+ {
36
+ test: /\.tsx?$/,
37
+ loader: "ts-loader",
38
+ exclude: ["/node_modules/", /\.d\.ts$/iu]
39
+ },
40
+ {
41
+ test: /\.d\.ts$/,
42
+ loader: 'ignore-loader'
43
+ },
44
+ // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
45
+ {
46
+ test: /\.js$/,
47
+ use: [
48
+ "source-map-loader",
49
+ {
50
+ loader: "babel-loader",
51
+ options: {
52
+ presets: ["@babel/preset-env"],
53
+ sourceMaps: true
54
+ }
55
+ }
56
+ ],
57
+ exclude: /(node_modules)/
58
+ },
59
+ {
60
+ test: /\.mjs$/,
61
+ exclude: /(node_modules)/,
62
+ type: "javascript/auto"
63
+ },
64
+ {
65
+ test: /\.wasm$/,
66
+ type: "asset/inline",
67
+ },
68
+ ],
69
+ parser: {
70
+ javascript: {
71
+ dynamicImportMode: 'eager'
72
+ }
73
+ }
74
+ },
75
+ plugins: [
76
+ // Work around for Buffer is undefined:
77
+ // https://github.com/webpack/changelog-v5/issues/10
78
+ new webpack.ProvidePlugin({
79
+ Buffer: ["buffer", "Buffer"]
80
+ }),
81
+ new webpack.ProvidePlugin({
82
+ process: "process/browser"
83
+ })
84
+ ],
85
+ // ignoreWarnings: [/Failed to parse source map/],
86
+ experiments: {
87
+ asyncWebAssembly: true,
88
+ topLevelAwait: true,
89
+ syncWebAssembly: true,
90
+ // futureDefaults: true,
91
+ },
92
+ mode: "production",
93
+ devtool: "source-map"
94
+ };
95
+
96
+ let nodeConfigs = merge(config, {
97
+ output: {
98
+ path: path.resolve(__dirname, "./dist/server"),
99
+ filename: "index.js"
100
+ },
101
+ resolve: {
102
+ fallback: {}
103
+ },
104
+ target: "node",
105
+ entry: ["babel-polyfill", path.resolve(__dirname, "./index.node.ts")],
106
+ externals: [
107
+ {
108
+ 'utf-8-validate': 'commonjs utf-8-validate',
109
+ 'bufferutil': 'commonjs bufferutil',
110
+ },
111
+ ],
112
+ });
113
+ let webConfigs = merge(config, {
114
+ output: {
115
+ path: path.resolve(__dirname, "./dist/browser/"),
116
+ filename: "index.js"
117
+ },
118
+ plugins: [
119
+ // new CopyPlugin({
120
+ // patterns: [{
121
+ // from: "./dist/browser/saito.js",
122
+ // to: "../../public/javascripts/saito.js",
123
+ // }]
124
+ // })
125
+ ],
126
+ resolve: {
127
+ fallback: {
128
+ "bufferutil": false,
129
+ "utf-8-validate": false
130
+ }
131
+ },
132
+ target: "web",
133
+ entry: ["babel-polyfill", path.resolve(__dirname, "./index.web.ts")],
134
+ });
135
+
136
+ module.exports = [nodeConfigs, webConfigs];
@@ -1,72 +0,0 @@
1
- import SharedMethods from "../../shared_methods";
2
- import Saito from "../../saito";
3
-
4
- export default class CustomSharedMethods implements SharedMethods {
5
- processApiCall(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): Promise<void> {
6
- throw new Error("Method not implemented.");
7
- }
8
-
9
- connectToPeer(peerData: any): void {
10
- throw new Error("Method not implemented.");
11
- }
12
-
13
- disconnectFromPeer(peerIndex: bigint): void {
14
- throw new Error("Method not implemented.");
15
- }
16
-
17
- fetchBlockFromPeer(url: string): Promise<Uint8Array> {
18
- throw new Error("Method not implemented.");
19
- }
20
-
21
- isExistingFile(key: string): boolean {
22
- throw new Error("Method not implemented.");
23
- }
24
-
25
- loadBlockFileList(): Array<string> {
26
- throw new Error("Method not implemented.");
27
- }
28
-
29
-
30
- processApiError(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): void {
31
- let promise = Saito.getInstance().promises.get(msgIndex);
32
- if (promise) {
33
- promise.reject(buffer);
34
- } else {
35
- console.error("callback not found for callback index : " + msgIndex + " from peer : " + peerIndex);
36
- }
37
- }
38
-
39
- processApiSuccess(buffer: Uint8Array, msgIndex: number, peerIndex: bigint): void {
40
- let promise = Saito.getInstance().promises.get(msgIndex);
41
- if (promise) {
42
- promise.resolve(buffer);
43
- } else {
44
- console.error("callback not found for callback index : " + msgIndex + " from peer : " + peerIndex);
45
- }
46
- }
47
-
48
- readValue(key: string): Uint8Array | null {
49
- throw new Error("Method not implemented.");
50
- }
51
-
52
- removeValue(key: string): void {
53
- throw new Error("Method not implemented.");
54
- }
55
-
56
- sendMessage(peerIndex: bigint, buffer: Uint8Array): void {
57
- throw new Error("Method not implemented.");
58
- }
59
-
60
- sendMessageToAll(buffer: Uint8Array, exceptions: Array<bigint>): void {
61
- throw new Error("Method not implemented.");
62
- }
63
-
64
- writeValue(key: string, value: Uint8Array): void {
65
- throw new Error("Method not implemented.");
66
- }
67
-
68
- sendInterfaceEvent(event: String, peerIndex: bigint): void {
69
- throw new Error("Method not implemented.");
70
- }
71
-
72
- }