Skip to content

Commit 137d62c

Browse files
committed
New wrapper using the node_modules approach
1 parent f91a969 commit 137d62c

3 files changed

Lines changed: 204 additions & 1 deletion

File tree

gems/wrapperV12.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// wrapperV11.js
2+
3+
/*
4+
This is the third working version of the wrapper. Better error handling and accepting multiple JavaScript commands for the secrets.js package.
5+
*/
6+
7+
// Hex to ASCII
8+
function hex2a(hex)
9+
{
10+
var str = '';
11+
for (var i = 0; i < hex.length; i += 2)
12+
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
13+
return str;
14+
}
15+
16+
// Require the secrets package and assign it to a variable
17+
const secrets = require('../node_modules/secrets.js-grempe/secrets.js');
18+
19+
// If the script is executed directly, call the appropriate function based on arguments
20+
if (require.main === module) {
21+
const commands = hex2a(process.argv[2]);
22+
23+
if (!commands.length) {
24+
console.error("No commands provided.");
25+
process.exit(1);
26+
}
27+
28+
try {
29+
30+
31+
//return commands;
32+
const inputData = JSON.parse(commands);
33+
34+
// Debugging statements
35+
//console.log("Commands received from Python:", commands);
36+
//console.log("inputData[0][0]: ", inputData[0][0]); // returns: init(33)
37+
38+
// Loop through commands
39+
for (const command of inputData) {
40+
// Evaluate each command
41+
lastResult = eval('secrets.' + command[0]);
42+
}
43+
44+
// Return the result of the last command
45+
console.log(JSON.stringify(lastResult));
46+
47+
} catch (error) {
48+
console.error("Error executing command:", error.message);
49+
process.exit(1);
50+
}
51+
}

gems/wrapperV12_test.py

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# wrapperV11_test.py
6+
7+
import json
8+
import subprocess
9+
10+
# Path to the Node.js wrapper script
11+
JS_FILE_PATH = "wrapperV12.js"
12+
13+
def wrapper(input_data):
14+
"""
15+
Run a JavaScript function using the Node.js wrapper.
16+
17+
Args:
18+
input_data (list): List containing the function calls as strings.
19+
20+
Returns:
21+
The result of the JavaScript function or None if there is an error.
22+
"""
23+
24+
# Enclose input_json in single quotes
25+
js_command = ["node", JS_FILE_PATH, input_data]
26+
27+
try:
28+
# Run the command and capture the output and stderr
29+
result = subprocess.run(js_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
30+
31+
# Debugging statement to print stdout and stderr
32+
# print("Input data sent to JavaScript:", input_data)
33+
# print("stdout:", result.stdout)
34+
# print("stderr:", result.stderr)
35+
36+
try:
37+
# Attempt to load the entire stdout as JSON
38+
js_result = json.loads(result.stdout)
39+
#print('json.loads')
40+
41+
# Print stderr if it exists
42+
if result.stderr:
43+
print("JavaScript stderr:", result.stderr)
44+
45+
return js_result
46+
47+
except json.JSONDecodeError as e:
48+
print("Python error decoding JSON:", e)
49+
print("Raw stdout content:", result.stdout)
50+
51+
except subprocess.CalledProcessError as e:
52+
# Print the error from the JavaScript script
53+
js_error = e.stderr.strip() # Use e.stderr instead of result.stderr
54+
print("JavaScript error:", js_error)
55+
return None
56+
57+
'''
58+
Used to pass a "clean" string as an arg to the CLI
59+
'''
60+
def encode_to_base36(data):
61+
base36_string = ""
62+
for key, value in data.items():
63+
base36_string += key + str(value)
64+
return base36_string
65+
66+
class JsFunction:
67+
def __init__(self, func, test=False):
68+
self.func = func
69+
self.test = test
70+
71+
def __call__(self, *args, test=False, **kwargs):
72+
def wrapped_func(*args, **kwargs):
73+
args_str = ', '.join(repr(arg) for arg in args)
74+
#kwargs_str = ', '.join(f'{key}={repr(value)}'
75+
# for key, value in kwargs.items())
76+
#all_args = ', '.join(filter(None, [args_str, kwargs_str]))
77+
78+
return f"{self.func.__name__}({args_str})"
79+
80+
data = []
81+
82+
# DO NOT REMOVE THIS
83+
if test or self.test:
84+
data.append("setRNG('testRandom')")
85+
86+
data.append(wrapped_func(*args, **kwargs) if args else self.func(*args, **kwargs))
87+
return data
88+
89+
def __get__(self, instance, owner):
90+
return self if instance is None else types.MethodType(self, instance)
91+
92+
@JsFunction
93+
def init(*args, **kwargs):
94+
pass
95+
96+
@JsFunction
97+
def setRNG(*args, **kwargs):
98+
pass
99+
100+
@JsFunction
101+
def share(*args, **kwargs):
102+
pass
103+
104+
@JsFunction
105+
def combine(*args, **kwargs):
106+
pass
107+
108+
alpha = init(18)
109+
bravo = setRNG("testRandom")
110+
delta = share('1234abc', 6, 3)
111+
112+
113+
# Combine
114+
tasks = [
115+
bravo,
116+
delta
117+
]
118+
119+
#tasks = {alpha, bravo}
120+
121+
#print("Tasks: ", tasks)
122+
123+
124+
125+
json_data = json.dumps(tasks, indent=None).replace("'", "`")
126+
#print(json_data)
127+
#print(json_data.encode().hex())
128+
data = json_data.encode().hex()
129+
#print(data)
130+
# Call the wrapper function
131+
shares = wrapper(data)
132+
133+
print(shares[1])
134+
print(shares[3])
135+
print(shares[5])
136+
137+
foobar = combine([shares[1], shares[3], shares[5]])
138+
tasks = [ foobar ]
139+
json_data = json.dumps(tasks, indent=None).replace("'", "`")
140+
data = json_data.encode().hex()
141+
print(wrapper(data))
142+
# print(shares)
143+
# #print(js_result)
144+
#
145+
# todo = combine([shares[2], shares[3], shares[4]])
146+
# json_data = json.dumps(todo, indent=None).replace("'", "`")
147+
# data = json_data.encode().hex()
148+
#
149+
# answer = wrapper(data)
150+
151+
152+
#print(answer)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@
88
"dependencies": {
99
"secrets.js-grempe": "^2.0.0"
1010
}
11-
}
11+
}

0 commit comments

Comments
 (0)