Giter Site home page Giter Site logo

woodser / monero-ts Goto Github PK

View Code? Open in Web Editor NEW
190.0 190.0 67.0 119.93 MB

TypeScript library for using Monero

Home Page: http://woodser.github.io/monero-ts/typedocs

License: MIT License

JavaScript 0.25% Shell 0.97% CMake 0.84% C++ 5.99% Python 0.03% HTML 0.02% TypeScript 91.90%
javascript monero nodejs rpc typescript typescript-library webassembly webpack

monero-ts's People

Contributors

beantosser avatar codeforcer avatar dependabot[bot] avatar dutu avatar lalvarezguillen avatar martyhav avatar samleegithub avatar tmoravec avatar trasherdk avatar woodser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

monero-ts's Issues

Make MoneroUtils run in the worker context

Functions in the class MoneroUtils require monero_wallet_keys.wasm to be pre-loaded even when the superset module is already loaded in the worker context. The solution is to move the execution of MoneroUtils functions into the worker context.

missing load_txt_records_from_dns

I try to create a new transaction but got this error:

missing function: ZN5tools9dns_utils25load_txt_records_from_dnsERNSt3__26vectorINS1_12basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEENS6_IS8_EEEERKSA

version: "monero-javascript": "^0.4.0"
nodejs version: 10.15.3

Error: Imported outputs omit more outputs that we know of

To send transactions using a view-only wallet and an offline wallet, I follow the doc - https://github.com/monero-ecosystem/monero-javascript/blob/master/docs/developer_guide/view_only_offline.md - and made one successful transaction. It was on chain and I can search it on the block explorer.

This is my code:

    // create and sync view-only wallet without spend key
    const viewOnlyWallet = await connectToWallet();
    await viewOnlyWallet.sync();

    // view-only wallet: export outputs
    const outputsHex = await viewOnlyWallet.exportOutputs();

    // create offline wallet
    const offlineWallet = await restoreWalletFull(privateSpendKey, from);

    // offline wallet: import outputs
    await offlineWallet.importOutputs(outputsHex);

    // offline wallet: export key images 
    const keyImages = await offlineWallet.exportKeyImages();
    console.log(JSON.stringify(keyImages))

    // view-only wallet: import key images
    await viewOnlyWallet.importKeyImages(keyImages);

    // view-only wallet: create unsigned tx
    const unsignedTx = await viewOnlyWallet.createTx({
        accountIndex: 0,
        address: to,
        amount,
    });

    // offline wallet: sign tx
    console.log(unsignedTx.getTxSet().getUnsignedTxHex()) // prints a hex string
    const signedTxHex = await offlineWallet.signTxs(unsignedTx.getTxSet().getUnsignedTxHex());
    
    // view-only wallet: submit signed tx
    const txHashes = await viewOnlyWallet.submitTxs(signedTxHex);
    console.log(txHashes)

But then from my second attempt on, it stuck at adding trust anchor: before throwing the error:

    Imported outputs omit more outputs that we know of
      211 |       let callbackId = GenUtils.getUUID();
      212 |       LibraryUtils.WORKER_OBJECTS[objectId].callbacks[callbackId] = function(resp) {  // TODO: this defines function once per callback
    > 213 |         resp ? (resp.error ? reject(new MoneroError(resp.error)) : resolve(resp.result)) : resolve();
          |                                     ^
      214 |       };
      215 |       worker.postMessage([objectId, fnName, callbackId].concat(args === undefined ? [] : GenUtils.listify(args)));
      216 |     });

or this error:

Failed to get height

      337 |   static _validateRpcResponse(resp, method, params) {
      338 |     if (!resp.error) return;
    > 339 |     throw new MoneroRpcError(resp.error.message, resp.error.code, method, params);
          |           ^
      340 |   }
      341 |   
      342 |   _setFakeDisconnected(fakeDisconnected) { // used to test connection manager

console.log(JSON.stringify(keyImages)) prints an empty array: []. I don't know if it has anything to do with the error. If not, what are likely causes of this error and what fixes it?

Publish as NodeJS module

This issue requests that the monero-javascript library be packaged and published as a NodeJS module.

Upgrade emscripten

The WASM included with the library is built using emscripten 2.0.24.

This issue requests building with the latest release of emscripten (currently 3.0.1).

Feature request: Decode unsigned tx set

As far as I can tell, if you have an unsigned tx string, there isn't a way to decode it into a MoneroTxWallet, which is printable with .toString()

I am looking to replicate something like the monero rpc command describe_transfer but with an offline wallet. The idea would be to allow a user to print the details of an unsigned tx, before signing it. Like

offlineWallet = openWalletFull(...)

moneroTxWallet.fromHex(unsigned_tx_str).toString()

.... if looks okay, then.....

offlineWallet.signTxs(unsigned_tx_str)

WASM wallet syncing leads to high latency in socket based application

I'm not sure if this is specific to monero-javascript or applies to all projects which utilize CPU demanding webassembly bindings.
I'm developing a socket based application and latency is critical. When the full wallet syncs in the background CPU usage spikes from 1% to over 30% which leads to other IO operations being delayed by multiple seconds. I mitigated this by using the wallet-rpc therefore offloading the intense processing to a separate process. It works fine but introduces extra complexity.
Is this to be expected or am I doing something wrong?

Monero Error is not defined

Please send help (My lvl: noob-grammer),

I ran into some issues earlier (which did not happen before) when creating New Wallet WASM. It seems to return a MoneroError but the problem is that I tried to catch it and says MoneroError is not defined (I think it's when it is creating a new Config as per the log file).

Just a quick question also. Does this have issues when the Library is called via Workers? I implemented workers that will handle each walletWasm opening as we are trying to open an array of wallets (which is a killer for my laptop).

Log error:

ReferenceError: MoneroError is not defined
    at new MoneroWalletConfig (/home/hcpioquinto/Desktop/work_files/Monero_backup/node_modules/monero-javascript/src/main/js/wallet/model/MoneroWalletConfig.js:45:9)
    at Function.createWallet (/home/hcpioquinto/Desktop/work_files/Monero_backup/node_modules/monero-javascript/src/main/js/wallet/MoneroWalletWasm.js:176:62)
    at Object.module.exports.createWalletWasm (/home/hcpioquinto/Desktop/work_files/Monero_backup/node_modules/monero-javascript/index.js:183:87)
    at MoneroWalletsHandler.createNewWallet (/home/hcpioquinto/Desktop/work_files/Monero_backup/moneroAPIClass.js:218:38)
    at MoneroWalletsHandler.onCreateWalletRequest (/home/hcpioquinto/Desktop/work_files/Monero_backup/moneroAPIClass.js:195:18)
    at /home/hcpioquinto/Desktop/work_files/Monero_backup/moneroAPIClass.js:307:20
    at Array.forEach (<anonymous>)
    at MoneroWalletsHandler.onImportWallets (/home/hcpioquinto/Desktop/work_files/Monero_backup/moneroAPIClass.js:301:23)
    at initThread (/home/hcpioquinto/Desktop/work_files/Monero_backup/newServer.js:124:38)
    at Object.<anonymous> (/home/hcpioquinto/Desktop/work_files/Monero_backup/newServer.js:137:3)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at MessagePort.<anonymous> (internal/main/worker_thread.js:162:24)
    at MessagePort.emit (events.js:315:20)
    at MessagePort.onmessage (internal/worker/io.js:78:8)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:11:10)

`stopProcess()` should return after process exits

Currently stopProcess() in MoneroDaemonRpc.js and MoneroWalletRpc.js returns after calling process.kill() without waiting to receive the kill signal callback.

As a result, the process may not be completely shut down before starting a new process which causes an error.

This issue requests changing stopProcess() to use process.exit() which terminates the process synchronously before returning.

[feature] Make it easier to use monero-javascript for front end development

For such a comprehensive and easy to use library for node, it's not possible to simply npm i monero-javascript and use it for front end/browser apps (yes, this is documented), and it's quite painful to integrate it with even basic create-react-app or vuejs boilerplate code. I think this is a big problem and is likely a bottleneck for a lot of would-be front end development.

I would really like to be able to simply install and use this library with no fussing with webpack and build configs if such a thing is possible.... i.e. I should be able to run create-react-app, or npm init vue@latest, run npm i monero-javascript, and be ready to roll.

Example of what needs to be done to use the library with Vue (see the fallbacks and additional packages necessary in package.json): https://github.com/xmrdotgift/wallet/blob/master/webpack.config.js

WASM module is not loaded; call 'await LibraryUtils.loadKeysModule()' to load

        import {
            MoneroUtils,
            MoneroNetworkType
        } from "monero-javascript";
        const result = MoneroUtils.validateAddress("45ENVMiz4MZV19MYYD3THkiaZ22eLEcB6KbNysSueNEa5sE5NdmnAGjhhMa3xgPttDC2SJji3bJiSdbpxg9VyNP55mGsLVD", MoneroNetworkType.MAINNET);
        console.log(result)

This code throws an error:

MoneroError: WASM module is not loaded; call 'await LibraryUtils.loadKeysModule()' to load
        at Function.validateAddress
        at verifyAddress
        at Object.<anonymous>
        at Object.asyncJestTest
        at new Promise (<anonymous>)
        at mapper {
      code: undefined

Vue.js integration

Installation
npm install monero-javascript --save

Test Code

<template>
	<h5>Blockheight: {{ height }}</h5>
</template>

<script>
import monerojs from 'monero-javascript'

export default {
	name: "Test",
	data(){
		return {
			height: 0
		}
	},
	async mounted() {
		let daemon = monerojs.connectToDaemonRpc("http://1.2.3.4:18089")
		let height = await daemon.getHeight()
		console.log(height)
		this.height = height
	}
}
</script>

Browser console error
Loading Worker from “http://localhost:8080/MoneroWebWorker.dist.js” was blocked because of a disallowed MIME type (“text/html”).

Not sure how to go about resolving this error. Are any additional steps necessary to integrate monero-javascript with Vue.js?

Implement remaining binary calls in MoneroDaemonRpc.js

The JavaScript client to daemon RPC already supports a number of binary calls. For example, getBlocksByHeight() uses the binary RPC call get_blocks_by_height.bin.

This issue requests support for the remaining unimplemented binary calls in MoneroDaemonRpc.js. Their implementation should follow the patterns of the already implemented binary calls, but may require additional processing like de-serializing some of the response fields which are also binary.

The remaining binary calls to be implemented are documented by the failing tests in TestMoneroDaemonRpc.js.

E !boost::string_ref{sig_str}.starts_with(header_v1) && !boost::string_ref{sig_str}.starts_with(header_v2)

I'm using the latest monero version ('Oxygen Orion' v0.17.2.0-release). The following code throws the error message in monero-wallet-rpc:

let wallet = await monerojs.connectToWalletRpc("http://127.0.0.1:8885", "admin", "admin");

await wallet.addListener(new class extends monerojs.MoneroWalletListener {
  onOutputReceived(output) {
    console.log(output) // result is ok
  }
});

E !boost::string_ref{sig_str}.starts_with(header_v1) && !boost::string_ref{sig_str}.starts_with(header_v2). THROW EXCEPTION: error::wallet_internal_error

Is there a way to suppress/fix it to avoid logging spam?

Missing notifications when restoring wallet without restore height or daemon connection

If a wallet is created without a restore height or daemon connection, the wallet estimates a restore height which may be greater than the current daemon height.

In this case, the library will not scan or provide notifications until it reaches its restore height.

As a result, some wallet data and notifications may be missing. This issue requests investigating missing scan data or notifications as a result of auto set restore height > daemon height.

ERROR: Building WebAssembly binaries from source

I followed the instructions for building WebAssembly binaries from source and got a compiler error:

em++: error: using 64-bit arguments in EM_JS function without WASM_BIGINT is not yet fully supported:js_send_binary_request(['const char* uri', ' const char* username', ' const char* password', ' const char* reject_unauthorized_fn_id', ' const char* method', ' const char* body', ' int body_length', ' std::chrono::milliseconds timeout'], [<Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>, <Type.I32: 127>]) [-Wem-js-i64] [-Werror]
I think this error is only in the newest version emsdk library. What is the latest correct version emsdk I should use to bypass the error?

[feature request] make integrated addresses for non wallet addresses

As discussed in the monero dev matrix channel it would be nice to have a way to create an integrated address that is not tied to the currently opened wallet. getIntegratedAddress(paymentId) on MoneroWalletFull is currently the only option to do this if we dont want to have an wallet rpc server.
If there is anything I can do to assist that effort let me know!

Daemon connection breaks because of a trailing "<"

When trying

let daemon = monerojs.connectToDaemonRpc("http://localhost:18081", "username", "password");
let height = await daemon.getHeight(); 

the console logs an error:

SyntaxError: Unexpected token '<'

I am sure it has nothing to do with my code, it only appears when pasting in the monero lib code.


Unrelated, but it may be worth investigating
Needs multisig export info from more participants
when syncing a 2/3 multisig wallet with just one msInfo, requesting to have the export ms data from both users when you actually just need one msInfo to perform the operation.

Build from source

Is there a recipe to build from source.
The description in README.md is not working.
export EMSCRIPTEN=<emsdk_root>/fastcomp/emscripten directory does not exist.
Running ./bin/build-emcpp.sh failing with:

fatal error: 'openssl/conf.h' file not found
     #include <openssl/conf.h>
              ^~~~~~~~~~~~~~~~

Webpack dependency error

While trying to run npm install -D webpack-cli, I got the following error:

npm WARN old lockfile 
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile 
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile 
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR!   dev webpack@"^5.50.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@"4.x.x" from [email protected]
npm ERR! node_modules/webpack-cli
npm ERR!   dev webpack-cli@"^3.3.12" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/jerf/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/jerf/.npm/_logs/2021-08-30T17_17_31_741Z-debug.lo

This was on commit 14a82fa.

[problem] edge case when creating transactions to self

When I parse a payment_uri with an integrated address like:
"monero:5F2AGUyXjR3bvX38GaAsARaQ1exeBCVkUbPTfGssBfXQ5VPor4eA144YpUE7FNg5bLcpEuehNne23MkG8ZMCkPEegecygCNXsmd1CnEenm?tx_amount=0.250000000000"
and pass the MoneroTxConfig to createTx I get this error:
Uncaught (in promise) RuntimeError: Aborted(Assertion failed: R == dbg_R, at: /Users/woodser/git/monero-javascript/external/monero-cpp/external/monero-project/src/crypto/crypto.cpp,450,generate_tx_proof). Build with -sASSERTIONS for more info.
I get the same error when I manually create a MoneroTxConfig with the integrated address.
So I assumed I ought to use decodeIntegratedAddress(integratedAddress) and pass the Standardaddress and PaymentId manually into the MoneroTxConfig. But when I do this, I get this error:

Error: Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead
    at LibraryUtils.WORKER_OBJECTS.<computed>.callbacks.<computed> (LibraryUtils.js:212:1)
    at Worker.LibraryUtils.WORKER.onmessage (LibraryUtils.js:188:1)

So it seems like the paymentId field for the MoneroTxConfig is the old style paymentId.
Creating transactions to standardaddresses works.

This was the code that I used on the server side to create the payment uri from this standard address:
75jZRMyxRMjbvX38GaAsARaQ1exeBCVkUbPTfGssBfXQ5VPor4eA144YpUE7FNg5bLcpEuehNne23MkG8ZMCkPEeTqtwPsG

async function(wallet, standardAddress, amount){
    wallet = await wallet
    let networkType = await wallet.getNetworkType();
    // get integrated address with randomly generated payment id
    await LibraryUtils.loadKeysModule();
    let integratedAddress = await MoneroUtils.getIntegratedAddress(networkType, standardAddress);
    //let paymentId = integratedAddress.getPaymentId(); // 16 characters write this to req.app.locals.payment or write it to the session
    let paymentUri = await wallet.createPaymentUri(new MoneroTxConfig().setAddress(integratedAddress.getIntegratedAddress()).setAmount(new BigInteger(amount)))
    return paymentUri;
}

maybe I messed up there somehow. It seems like I dont get out the same standard address that I put in. I will make a paymenturi with just a standard address and see if that works. EDIT: It works. So this issue most likely arises because I make faulty integrated addresses. I will verify again with a know good integrated address.
A known good integrated address produced a different error message: Invalid destination address at LibraryUtils.WORKER_OBJECTS.<computed>.callbacks.<computed> (LibraryUtils.js:212:1) at Worker.LibraryUtils.WORKER.onmessage (LibraryUtils.js:188:1)
so it seems like it still needs to be processed somehow before it can be fed into createTx.
EDIT again: this might be because the known good address is a mainnet address and I a m on stagenet. So maybe integrated addresses work fine, I just picked the wrong net. In either case the error message is less spooky
EDIT again AGAIN: I tried again with a stagenet integrated address. This time it worked without issues. So the issue is narrowed down to the integrated address creation process. I think it might lead to trouble because I use Moneroutils to generate an integrated address for a wallet that is different from the wallet that is currently opened with monerowalletfull. I want to do this because the backend should be able to create new integrated for addresses of users that we dont have the viewkeys for.
EDIT. the integrated address from above works when creating a transaction with the gui wallet, but it still produces the same error when creating a transaction with this library. I setloglevel to 10 but it didnt gain any new insights. I will try further and figure out where the issue is :-)

EDIT: I think I can reproduce it now: 1.create subaddress. 2. make integrated address with subaddress 3.create transaction to this integrated address. => leads to the crash with "Assertion failed: R == dbg_R," Conditions: it needs to be a subaddress of the same wallet. ( so essentially sending to ones own wallet subaddress with an embedded payment id leads to this it. side effect: decodeIntegrated address also leads to unexpected output with this address) Monero GUI also shows an error message for this. the question is how to best deal with it. getting users to create these tx leads to crashes. I will write a test case for this when I have more time.

exportKeyImages is not working

I am followed the guide https://github.com/monero-ecosystem/monero-javascript/blob/master/docs/developer_guide/view_only_offline.md for the offline transaction signing. The guide is incorrect because "async" could not be used without await. So i wrote my own code:

const monerojs = require("monero-javascript");

if (monerojs.LibraryUtils.WORKER_DIST_PATH.indexOf("C:") == 0 && monerojs.LibraryUtils.WORKER_DIST_PATH.indexOf("file://") == -1)
    monerojs.LibraryUtils.WORKER_DIST_PATH = "file://"+monerojs.LibraryUtils.WORKER_DIST_PATH;

async function test()
{
    const walletNameView = "ViewWallet"
    const walletNameOffline = "OfflineWallet"
    const primaryAddress = "58xgBuuMYGFWnwkBNHZRUn4s613XhQCNx2eMkoqgPJfuZWnXH4HMh9WYQ6KVtLq3TJ4szc1AEZi98H8fLXDekkn7KGgVTMz";

    const privateViewKey = "a15a2245c51fcb50f2bad06a05af68926e4a730efc0cc8b42e9e06a430a84100";
    const privateSpendKey = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b800";

    try {
        const RPC = require("./source/private").RPC.txmr || false;
        if (!RPC) throw new Error("RPC not found")
                
        const daemon = await monerojs.connectToDaemonRpc(RPC.host, RPC.user, RPC.password);
        if (!daemon.isConnected) throw new Error("Daemon not connected!");
 
        const height = await daemon.getHeight();   
        
        let viewOnlyWallet = await monerojs.MoneroWalletFull.walletExists(walletNameView) ?
            await monerojs.openWalletFull({
                path: walletNameView,
                networkType: "stagenet",
                password: "supersecretpassword123",
                server: {uri: RPC.host, username: RPC.user, password: RPC.password}
            }) :
            await monerojs.createWalletFull({
                path: walletNameView,
                networkType: "stagenet",
                password: "supersecretpassword123",
                primaryAddress: primaryAddress,
                privateViewKey: privateViewKey,
                restoreHeight: height - 1000,
                server: {uri: RPC.host, username: RPC.user, password: RPC.password}
            });

        if (! await viewOnlyWallet.isConnectedToDaemon()) throw new Error("wallet not connected to daemon")

        if (! await viewOnlyWallet.isSynced())
            await viewOnlyWallet.sync(); 

        // create offline wallet
        let offlineWallet = await monerojs.createWalletFull({
            path: walletNameOffline,
            networkType: "stagenet",
            password: "supersecretpassword123",
            primaryAddress: primaryAddress,
            privateSpendKey: privateSpendKey
        });

        const balance = await viewOnlyWallet.getBalance();
        console.log(balance.toJSValue());

        // export outputs from view-only wallet
        const outputsHex = await viewOnlyWallet.exportOutputs();

        // import outputs to offline wallet
        await offlineWallet.importOutputs(outputsHex);

        // export key images from offline wallet
        let keyImages = await offlineWallet.exportKeyImages();

        await viewOnlyWallet.importKeyImages(keyImages);

        // create unsigned tx using view-only wallet
        ret = await viewOnlyWallet.createTx({
            accountIndex: 0,
            address: primaryAddress,
            amount: "100"
        });

        await viewOnlyWallet.save();
        await viewOnlyWallet.close();
    }
    catch(e) {
        console.log(e);
    }   
}

test();

This my code is working well but it seems that the call await offlineWallet.exportKeyImages(); is returning an incorrect value: Array(0).
Has anyone been able to export key images? Has this feature been tested at all?

Improve import mechanism

Currently when I use the recommended mechanism of doing require('monero-javascript') my sensible editor wonders where I'm pulling the suddenly defined classes from. While the code itself works this is quite annoying as it would require me to disable eslint. Furthermore importing everything always is not very efficient. I see that when you import monero-javascript what is actually being done in the background is that a function is called that globally defines all the classes and functions. Could you please use a standard form of module exports? I'd much appreciate it!

Remove timeout

I have a project in which I'm building a new database by using .getBlockByHeight(). Probably not the most efficient way but it works so far. Sometimes I get a 30000 ms timeout like below. Is there a way to increase or disable this timeout? It doesn't usually happen on stagenet, but I notice it more on mainnet. Also I'm running these processes behind multiple docker containers, if that is related.

Error: Request timed out in 30000 milliseconds
1|analitik |     at LibraryUtils.WORKER_OBJECTS.<computed>.callbacks.<computed> (/infosec/analitiko/node_modules/monero-javascript/src/main/js/common/LibraryUtils.js:212:37)

Edit: this could be a networking thing on my side, I just checked again and it might be happening on these dynamic ip changes with the containers. Will keep an eye out for the next and close this issue if that is the case.

Support a client-side Monero wallet in JavaScript

This issue requests support for a client-side Monero wallet whose only dependency is a daemon in order to synchronize blocks and maintain wallet state locally.

The wallet will not share its view key with a 3rd party in order to offload processing of incoming transactions.

The preferred implementation is to refactor Monero Core's wallet2 in order to separate core wallet cryptography and functionality from bundled dependencies so that the Core wallet can run in the browser using wasm. More generally, refactoring wallet2 will allow applications to access the Monero Core wallet in different runtime environments more easily. This has been discussed and generally supported among Monero Core developers pending a pure, "algebraic" refactor of wallet2.

Some client-side wallet functionality can be supported without being a full wallet, like local generation of a seed and generating/querying subaddresses. Some of this has already been implemented in MoneroWalletLocal.js (needs updating at time of writing).

Support HTTPS.

HTTPS seams not supported.

  let walletRpc = new MoneroWalletRpc(
    "https://x.x"
  )
  await walletRpc.openWallet("x", "x")

Error:

(node:12037) UnhandledPromiseRejectionWarning: Error: RequestError: TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:" at MoneroRpcConnection.sendJsonRequest (/home/user/Projects/jointed.gitlab.io/docker/node_modules/monero-javascript/src/main/js/rpc/MoneroRpcConnection.js:124:18)

It is possible to connect to monero-wallet-rpc over https with curl.

curl -X POST https://x.x/json_rpc -d '{"jsonrpc":"2.0","id":"0","method":"open_wallet","params":{"filename":"x","password":"x"}}' -H 'Content-Type: application/json'
{
  "id": "0",
  "jsonrpc": "2.0",
  "result": {
  }
}

Switch to async fs api

This issue requests switching to asynchronous fs calls which are better supported across environments.

Connecting to a wallet RPC: Method not found

I'm trying to connect Monero wallet RPC (for tests to an open node) based on docs and tests and haven't succeeded yet. I've described several attempts at stackexchange and here I'll focus on one approach.

I've generated a valid mnemonic (here), generated keys and address offline and have send some test tokens to the address via the faucet. I'm trying to connect to wallet RPC using a node (currently https://testnet.xmr.ditatompel.com) taken from the list of public nodes (with this node, I've successfully called get_block_count JSON RPC method and get_transactions PRC method of Daemon RPC, so it works at least with those). However, I'm not sure if each node supporting Daemon RPC also supports Wallet RPC (please help me clarify that).

Now, here's my attempt in the nutshell:

const walletRpc = await monerojs.connectToWalletRpc({
    uri: nodeUri, // actually, I've tested all the 4 currently available nodes for testnet, the result is the same for each one
    username: "rpc_user", // not sure how these are managed; tested without username/password as well, same result
    password: "abc123",
});
// console.log(walletRpc) shows MoneroWalletRpc with the provided config details and MoneroRpcConnection details
// console.log(walletRpc.createWallet) and console.log(walletRpc.openWallet) show [AsyncFunction: createWallet] and [AsyncFunction: openWallet] respectively

// this failes with "Method not found"
const result = await walletRpc.createWallet({
    // networkType: moneroNetwork,
    mnemonic,
});

Why createWallet fails? Is it supposed to only work with a local node? If there is a way to create a wallet/connect to it using a public node, please help me figure what's wrong with this attempt.

I've also tried

const res = await walletRpc.openWallet({
    // networkType: moneroNetwork,
    mnemonic,
});

which fails "Must provide name of wallet to open", so I guess I do have to create the wallet first.

Create new address for account?

Is there a way to create a new subaddress for an account? I don't see any method listed in /src/main/js/wallet/model/MoneroAccount.js

Cannot open_wallet if the same wallet is opened by `monero-wallet-rpc`

If a wallet is opened by monero-wallet-rpc, attempting to re-open it via daemon.openWallet() throws exception error with appropriate message on RPC console:

E !is_keys_file_locked(). THROW EXCEPTION: error::wallet_internal_error

That is inconvenient if you need to restart your node application and still work with the same wallet -> you have to restart monero-wallet-rpc as well, or manually close the wallet (method which also is not supported by library)

Working on a PR to fix it.

Hardcoded path to MoneroWebWorker.dist.js

Good Evening,

currently I am creating an web-application based on your sample app. With the given instructions its super easy to start the application and work with the library.

But when I extend the source with a new page lying in a subdirectory, the library tries to load the "MoneroWebWorker.dist.js" worker code from this directory e.g.

Does work:

<!-- /index.html -->
<script type="text/javascript" src="/sample_code.dist.js"></script>

Result: GET http://localhost:9100/subfolder/MoneroWebWorker.dist.js 200 OK

Does not work:

<!-- /subdirectory/index.html -->
<script type="text/javascript" src="/sample_code.dist.js"></script>

Result: GET http://localhost:9100/subfolder/MoneroWebWorker.dist.js 404 (File not found)

A quick look at the source code made the problem obvious:

https://github.com/monero-ecosystem/monero-javascript/blob/307f09f1627ed16e967599887e6dd9a781440196/src/main/js/common/LibraryUtils.js#L133

I don't know whether this script needs to be referenced relative or not. Are there any plans to change this behaviour? Right now I'm forking the project and specifying the absolute path by hand but this seems to be a bit of an overkill for this small change.

Thank you for your attention to this matter.

Cannot sign transaction offline with the example - https://github.com/monero-ecosystem/monero-javascript/blob/master/docs/developer_guide/view_only_offline.md

To sign a transaction offiline, I follow the code from the doc: https://github.com/monero-ecosystem/monero-javascript/blob/master/docs/developer_guide/view_only_offline.md.

let viewOnlyWallet = await connectToWalletRpc("http://localhost:18082");
await viewOnlyWallet.sync();
    
// export outputs from view-only wallet
let outputsHex = await viewOnlyWallet.exportOutputs();
console.log(outputsHex)

// create offline wallet
let offlineWallet = await createWalletFull({
     networkType: MoneroNetworkType.MAINNET,
     privateSpendKey,
     primaryAddress: from,
     password: "password",
});

// import outputs to offline wallet
await offlineWallet.importOutputs(outputsHex);
// prints`4d6f6e65726f206f7574707574206578706f7274046bf1054864f10b1ba7fbe20898ad13e1a3a3c6dcc78d9ac9e8ec15bca8cc1198c50092d27077d6d678b442629e9cf229fe2beaceb7186cd9ea1eef561aac25973f3ad55431351c805c0dc9376f49c58b7fb2b4487d8143b725269495ffa9cadbe36a8d7ce3982cce2f1006fcea60c432c72e2acedeaecf4f64c59fa2aa996d110d296dddfeade796b80306`

// export key images from offline wallet
let keyImages = await offlineWallet.exportKeyImages();
console.log(JSON.stringify(keyImages))
// prints an empty array []

// import key images to view-only wallet
await viewOnlyWallet.importKeyImages(keyImages);
        
// create unsigned tx using view-only wallet
const unsignedTx = await viewOnlyWallet.createTx({
     accountIndex: 0,
     address: to,
     amount,
});

console.log(unsignedTx.getTxSet())
// prints MoneroTxSet {
      state: {
        multisigTxHex: undefined,
        unsignedTxHex: undefined,
        signedTxHex: undefined,
        txs: [ [MoneroTxWallet] ]
      }
    }

// describe unsigned tx set to confirm details
const describedTxSet = await offlineWallet.describeTxSet(unsignedTx.getTxSet());

The last line above throws an error: no txset provided. But I suppose it's already wrong at lineconsole.log(JSON.stringify(keyImages)) when it prints an empty array [].

Offline wallet and View only wallet using Monero Wallet RPC.

I was trying to test this library in a scenario very similar to the one described here, the main difference is that the view only wallet is using the standard monero-wallet-rpc binary.

I exported the outputs hex using the export_outputs method and created an unsigned transaction using the transfer method, getting in both cases an hex of the required data. When trying to use this data in the MoneroWalletFull offline wallet I get the following:

> await this.wallet.importOutputsHex("<outputs_data_hex>");
0
> await this.wallet.signTxs("<unsigned_txset_hex>");
undefined

It is very likely that I'm missing some intermediate step, such as getting the transaction hex from the unsigned_txset, however I couldn't find any information about it.

Is there any documentation, guide or example available on how to do this?

Build with latest emsdk leads to runtime error in monero_core.wasm

When building wasm via emsdk 2.0.4, the creation of a random wallet ( and I think of any wallet ) will throw a Segmentation fault. monero_core_keys seems still to work. Going back to emsdk 1.40 resolves this issue.
No idea at which version this error starts to occur.
The changelog ( 2.0.4 ) states:

Stop including malloc and free by default. If you need access to them from
JS, you must export them manually using
-s EXPORTED_FUNCTIONS=['_malloc', ..].

https://emscripten.org/docs/introducing_emscripten/release_notes.html#changelog

I did try that without success.

Disable debug messages

I'm integrating monero-javascript into my most recent project and it's working great so far.
However these debug sync messages are spamming my logs. Is it possible to disable them?

Example:

Heap resize call from 16777216 to 20185088 took 0.09554499387741089 msecs. Success: true
Heap resize call from 20185088 to 24248320 took 0.0572359561920166 msecs. Success: true
Heap resize call from 24248320 to 29097984 took 0.3719410300254822 msecs. Success: true

Getting 401 error: unauthorized when using createWalletWasm() with local node

versions:
monero-javascript 0.4.3
monerod v0.16.0.3
node v14.9.0
npm 6.14.8
react 16.13.1
babel core 7.11.4
webpack 4.44.1
webpack-dev-server 3.11.0

usage:
./monerod --stagenet --rpc-login superuser:abctesting123 --rpc-access-control-origins http://localhost:8080

then I start the webpack-dev-server on http://localhost:8080

relevant code:

const monerojs = require("monero-javascript");

let walletRpc = new monerojs.MoneroRpcConnection({
  //uri: "http://stagenet.community.xmr.to:38081",
  uri: "http://localhost:38081",
  username: "superuser",
  password: "abctesting123",
  rejectUnauthorized: false, // e.g. local development
});

export async function createWallet(lang = "English") {
  console.log("Creating new wallet");
  let walletWasm = await monerojs.createWalletWasm({
    networkType: "stagenet",
    language: lang,
    password: "pass123",
    server: walletRpc,
  });
  return walletWasm;
}

error:
on host system macOS 10.15.6
for both Firefox 80.0.1 and Brave 1.13.82 (Chromium 85.0.4183.83)
in the browser console:

XHRPOSThttp://localhost:38081/json_rpc
[HTTP/1.1 401 Unauthorized 0ms]

If I try to use the JSON RPC with Postman I get it to work, but not with monero-javascript and the WASM Wallet in the browser. Am I doing something wrong?

Thanks!

curl: (7) Failed to connect to 127.0.0.1 port 18082: Connection refused

After running the following CURL command on my local PC:

curl \

-X POST http://127.0.0.1:18082/json_rpc \
-d '{"jsonrpc":"2.0","id":"0","method":"'make_integrated_address'","params":'"{\"payment_id\":\"1234567890123456789012345678900012345678901234567890123456789000\"}"'}' \
-H 'Content-Type: application/json'

I am getting the Connection Refused problem. Anyone Please help

FYI, I am following the documentation here:
https://monerodocs.org/interacting/monero-wallet-rpc-reference/

Support a MyMonero-compatible wallet

This issue requests support for an implementation of the MoneroWallet.js interface which allows the wallet's view key to be shared with a 3rd party in order to offload processing of incoming transactions.

By implementing the MoneroWallet.js interface, the adapter will conform to this library's specification and plug into existing tests.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.