PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cryptocurrency. Show all posts
Showing posts with label cryptocurrency. Show all posts

Sunday, September 25, 2022

[FIXED] How hashes for blocks are created in ethereum?

 September 25, 2022     bitcoin, blockchain, cryptocurrency, ethereum, solidity     No comments   

Issue

So according to my understanding of bitcoin, we change the value of nonce to create new hashes for a block until we get a hash within the target.

But in case of ethereum "The nonce, a counter used to make sure each transaction can only be processed once" is incremented by one for each transaction according to my understanding, please correct me if I'm wrong.

My question is if we cannot use random values for nonce in ethereum block to change the hash values and get a value within target then what changes we make to the block data how do we change hash values to get a value within target?


Solution

The proof of work (PoW) algorithm works in the same way in bitcoin and ethereum. There is also nonce in ethereum block header. Official documentation, called yellow paper, in section 4.3 says:

(...) The block header contains several pieces of information: (...)

nonce: A 64-bit value which, combined with the mixhash, proves that a sufficient amount of computation has been carried out on this block; formally Hn.

In the same document, in section 4.2, is explained nonce for transaction.

Just to summarize: In ethereum nonce appears in 2 places, in transaction and in block header. In transaction nonce works in the way you've described. In block header nonce works like in PoW. Both nonces are independent of each other.



Answered By - kj-crypto
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to reserv your own crypto currency name?

 September 25, 2022     ape, blockchain, cryptocurrency, ethereum, merit-gem     No comments   

Issue

I have come to learn about ape coin recently. But I am not sure how are they restricting people from naming a new cryptop currency with 'Ape Coin'?

Dothey have patents or something?

Why am I asking this question? What if I create a crypto-currency and some steals the unique name of my currency? That will create a confusion among the users. And they may start using stolen coin unknowingly?


Solution

Ethereum and most other crypto networks are decentralized, without any authority or mechanism controlling token names.

So it's technically possible to create another Ape Coin, even with the very same functionality.

Some centralized services such as Coinmarketcap might deny listing of these obvious copies of famous coins on their service. And some semi-decentralized services such as Uniswap have a list of verified token addresses and show a warning if you're about to trade a token that is not on this list.

But generally, the network is not stopping two separate authors to both create a token and both name it "XYZ".



Answered By - Petr Hejda
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How exchanges (Binance, Coinbase) record user trade into blockchain

 September 25, 2022     binance, blockchain, coinbase-api, cryptocurrency     No comments   

Issue

My question is how cryptocurrency exchanges like Binance or Coinbase record users trade into blockchain technically. For example when Mr.X buys BTC/USDT pair from Mr.Y, how does the exchange record these two Transactions into the blockchain. as far as I know, We have two transactions now, Mr.X has to sign a USDT transaction to Mr. Y's account & Mr.Y has to sign a transaction for Mr. X's BTC wallet on that exchange. I was wondering how exchanges manage network fees? & how they record these trades into blockchain I also know Mr.X order will probably fulfill with different accounts but I just want to simplify my question thank you.


Solution

As far as I know both of them are centralized entities so what happens is:

Mr X and Mr Y send their crypto to the exchange controlled wallets. The exchanges keep the record in their own DB/ledger who owns what. Then when Mr Y and Mr X make a trade the exchanges record that trade in their own DB/ledger and nothing is recorded on public blockchain. Now Mr X withdraws the crypto from one of the exchanges and it gets recorded on public blockchain (If he withdraws BTC then it will be recorded on BTC blockchain). So Mr X and Mr Y can do thousands of trades without paying network fees as everything happens in the exchange's internal system (they may have per trade fee)

DeFi - I have no idea how it works, as didn't dig into it :)



Answered By - Tom
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to register name and log in my solana token on devnet

 September 25, 2022     blockchain, cryptocurrency, nft, solana     No comments   

Issue

Everyone. I have minted my token on solana devnet. But I don't know to change the token name and log. I need help in this problem. enter image description here


Solution

At the time of writing, the solana explorer pulls all the token images, names, and descriptions from the token-list repo.

You'll have to submit a PR with your token's details to get it updated on the explorer and a variety of wallets.



Answered By - Jacob Creech
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How to connect Metamask to Web3J (java)

 September 04, 2022     authentication, cryptocurrency, java, metamask, web3-java     No comments   

Issue

I am trying to connect my Metamask wallet to my Java Spring-Boot backend. I was trying to follow the example here. I am able to autogenerate the nonce and receive the wallet ID without a problem. I am trying to verify the signed nonce from the Wallet on the server to make sure that the sender is indeed who they say they are. However, I am unable to find any documentation on Web3J to do this.

Is web3j not the right package to use for this? The example shows how to do the verification on NodeJS based on javascript but I don't find any example on how to do this on Java.

My understanding is that the public key is the wallet ID itself and that the message is the nonce signed by the private key of the wallet which is not shared for obvious reasons. According to this, I would need to "decrypt" the message using the public key and see if the decrypted message is same as the nonce that the backend sent to Metamask to sign. Is this correct?

Here is my code to create and send the nonce to UI:

public User findUserByPublicAddress(String publicWalletId) {
    User u = userRepository.findByPublicWalletId(publicWalletId);
    if(u == null) {
        u = new User("", "", "", null, publicWalletId, "");
        String nonce = StringUtil.generateRandomAlphaNumericString();
        u.setNonce(nonce);
        userRepository.saveAndFlush(u);
    }
    return u;
}

Here, I see if the user is already in my system and if they are not, then I just create a temporary user with a random nonce generated and saved in the DB. This nonce is sent to the UI for Metamask to sign. However, I am not sure how to do the verification part of it.


Solution

I was able to figure this out finally. My initial understanding was incorrect. I was not supposed to attempt to decrypt the message to retrieve the nonce. Rather I needed to use the nonce to see if I can retrieve the public key of the private key used to sign the message and see if that public key retrieved matches the wallet ID.

The algorithm:

  1. Receive the signed message and the wallet ID from the client
  2. Retrieve the nonce sent to the client with the same wallet ID
  3. Generate the hash of the nonce
  4. Generate the signature data from the message. This basically retrieves the V, R and S and. R and S are the outputs of the ECDSA Signature and V is the Recovery ID.
  5. Using the ECDSA Signature and Hash of the Nonce, generate the possible public Key that was used to sign the message. At max, one will be able to generate 4 possible public keys for this message.
  6. Check if any of the generated keys match public wallet ID that the client sent. If it matches, then we have a positive match. Generate the JWT and respond to the client. If not, we know that the nonce was not signed by the Metamask wallet we expected.

The Code:

Here is a sample code for UI (JavaScript and HTML):

web3.eth.sign(
    web3.utils.sha3(nonce),
    window.userWalletAddress)
.then((message) => {
    console.log(message)
    data['message'] = message // BODY
    var xmlReq = new XMLHttpRequest();
    xmlReq.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            response = this.responseText
            console.log(response)
        }
    };
    xmlReq.open("POST", "/api/users/login", true)
    xmlReq.setRequestHeader('Content-Type', 'application/json')
    xmlReq.send(JSON.stringify(data))
})

The web3.eth.sign() takes the message to be signed and takes the wallet ID that is signing it. This is then sent to the backend. In the backend:

public User signin(UserLoginDTO loginDetails, HttpServletResponse response) {
    try {
        // Get the wallet ID and signed message from the body stored in the DTO
        String publicWalletId = loginDetails.getPublicWalletId();
        String message = loginDetails.getMessage();

        // Find the nonce from the DB that was used to sign this message
        User user = userRepository.findByPublicWalletId(publicWalletId);
        String nonce = user.getNonce();

        // Generate the HASH of the Nonce
        byte[] nonceHash = Hash.sha3(nonce.getBytes()) // org.web3j.crypto.Hash

        // Generate the Signature Data
        byte[] signatureBytes = Numeric.hexStringToByteArray(message); // org.web3j.utils.Numeric
        
        byte v = (byte) ((signatureBytes[64] < 27) ? (signatureBytes[64] + 27) : signatureBytes[64]);
        byte[] r = Arrays.copyOfRange(signatureBytes, 0, 32);
        byte[] s = Arrays.copyOfRange(signatureBytes, 32, 64);
        
        SignatureData signatureData = new SignatureData(v, r, s); // org.web3j.crypto.Sign.SignatureData

        // Generate the 4 possible Public Keys
        List<String> recoveredKeys = new ArrayList<>();
        for(int i = 0; i < 4; i++) {
            BigInteger r = new BigInteger(1, signatureData.getR());
            BigInteger s = new BigInteger(1, signatureData.getS());
            ECDSASignature ecdsaSignature = new ECDSASignature(r, s);
            BigInteger recoveredKey = Sign.recoverFromSignature((byte)i, ecdsaSignature, nonceHash);
            if(recoveredKey != null) {
                recoveredKeys.add("0x" + Keys.getAddressFromKey(recoveredKey)); // org.web3j.crypto.Keys
            }
        }

        // Check if one of the generated Keys match the public wallet ID.
        for(String recoveredKey : recoveredKeys) {
            if(recoveredKey.equalsIgnoreCase(publicWalletId)) { 
                // Add Code here to create the JWT and add that to your HttpServletResponse. Not shown here.
                return user;
            }
        }
        throw new CustomException("Message Sign Invalid", HttpStatus.UNAUTHORIZED);
    }
    catch (Exception ex) {
         // Custom Error Handling.
    }
}


Answered By - whiplash
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 28, 2022

[FIXED] How can I reward addresses with who add liquidity to the pool? (ERC20 token)

 July 28, 2022     blockchain, cryptocurrency, erc20, ethereum, solidity     No comments   

Issue

If an address swaps ETH for my_token, I wanna reward them with free my_tokens (calculated as a % of the transaction). Would it be possible to implement it in the solidity code or are there any built-in solutions on uniswap, pancakeswap etc.


Solution

This is how it is usually done with liquidity mining.

  • When you add liquidity you receive LP token of the pool (liquidity provider token(
  • Then you lock these LP tokens to a vault
  • As long as the LP tokens are locked, the user is receiving rewards

One of the most well-known contracts for such liquidity mining is MasterCher from Sushiswap.

I suggest

  • You try liquidity mining yourself by buying some token subject to liquidity mining
  • Then see how MasterChef could be applied for your project


Answered By - Mikko Ohtamaa
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where and how does blockchain gets stored?

 July 28, 2022     bitcoin, blockchain, cryptocurrency, networking, smartcontracts     No comments   

Issue

I'm trying to visualize the concept of blockchain with real-world example. So let's say I want to purchase bitcoin. As the concept of blockchain is decentralization, the transaction will be hashed and stored in "every node" within the "network". Here is where I have question on.

  • From what I understand so far, "every node" is basically every computer within the blockchain network. So that means it must be stored somewhere in my computer locally right? So where exactly will it be stored and how does it ensure that my computer is part of the "network"? Is there some kind of software I need to download and execute to be part of the "network" or something?

  • As every time there's a new transaction happening in the network, my blockchain stored in my computer should update its data with new transaction. As more and more transaction happens, wouldn't the size of my blockchain data also increase? What if I only have limited storage?

  • What if I'm using a mediator like Coinbase? And let's assume majority of people purchasing cryptocurrency are using Coinbase. Doesn't this mean the blockchain is no longer decentralized due to the fact that one or couple of mediators own all the data?

  • What if there are only 2 nodes for a blockchain (me and my friend maybe)? Does this mean if I hack other person's computer and change its value, there's no ways to verify data authenticity? Isn't this similar to how smart contracts work (network with very few nodes)?


Solution

it must be stored somewhere in my computer locally right?

Correct. In order to become a peer in the Bitcoin network, you need to run a Bitcoin client software. For example the original bitcoind. Its data, including the raw blockchain database, is stored in a folder on your drive - either the default location or configured.

What if I only have limited storage?

Then your client software won't be able to sync any longer and will stay out of sync with the rest of the network. Depending on the specific software, you might still be able to see your transactions before this event, might be able to sign and broadcast transactions, but won't know (from within the software) if they were accepted by the network or not. E.g. because you might be trying to spend more than you have at the moment, but the wallet is not reflecting your last transactions and current balance as it's not synced.

What if I'm using a mediator like Coinbase?

The amount of decentralization might be also perceived on a scale. In that case, the more people use custodial wallets such as Coinbase, the less decentralized is the network. But that might not be binary - "decentralized or not" - just "less decentralized than 100% users running their own node".

What if there are only 2 nodes for a blockchain

This is called the 51% attack. In this scenario of just 2 nodes in the network, you might be able to successfully perform the attack.

Isn't this similar to how smart contracts work

Bitcoin has a very limited possibility of scripting transactions - its scripting language is not Turing complete and is practically used "just" for multisig transactions. So I'm assuming you mean smart contracts on Ethereum and other platforms. These smart contracts produce a list of state changes (e.g. balance of an address or storage value of a smart contract) and this process and its result is validated by other peers in the network as well (again if it's produced in accordance with rules of the network). So smart contracts are not really related to the 51% attack.



Answered By - Petr Hejda
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Create a tron wallet with nodejs

 July 28, 2022     blockchain, cryptocurrency, node.js, tron     No comments   

Issue

I want to create a TRON web wallet but I`m completely a noob in it. My first question is how do I generate addresses offline and with a private master key or with mnemonic seeds The second question is how can I query the balance of all addresses generated by me with a single request to TronGrid?


Solution

Assuming you have TronWeb installed.

You can do TronWeb.createAccount() to generate an address and save the output, example from docs.

You may need to check balance of address one by one by posting to TronGrid, https://api.trongrid.io/wallet/getaccount, example from docs



Answered By - Ming
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 22, 2022

[FIXED] Blake2b-512 with ED25519 in PHP with NanoSalt library (Nano Crypto)

 January 22, 2022     cryptocurrency, cryptography, ed25519, php     No comments   

Issue

I'm trying to generate a Nano private key, public key and address (that's a cryptocurrency) in PHP. I successfully generated private keys but I'm not able to generate the public key and consequently neither the checksum nor the integer address. in order to do this I would have to encrypt the private key through the blake2b-512 algorithm and the ED25119 curve and then I gotta obtain the checksum through the blake2b-40 algorithm by encrypting the public key. That's my code:

$privatekey = strtoupper(bin2hex(random_bytes(32)));
$publickey = sodium_crypto_sign_ed25519_pk_to_curve25519($private_key);
$checksum = hash(blake2b-40, $publickey);

I didn't get what I need. Why?

UPDATE 30/12/2021 13:36

I'm trying to resolve the update with the NanoSalt library but it gives me this error:

index.php

<?php
use MikeRow\Salt\NanoSalt;

$nanoSalt = new NanoSalt();
$public_key = $nanoSalt->crypto_sign_public_from_secret_key(hex2bin("781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3"));
print(strtoupper($public_key->toHex()) . PHP_EOL);
?>

and that's the error:

Fatal error: Uncaught Error: Class "MikeRow\Salt\NanoSalt" not found in C:\xampp\htdocs\Peppe\index.php:4 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Peppe\index.php on line 4

Solution

Nano does not use the standard Ed25519, but a variant where the digest Blake2b-512 is used instead of the usual SHA-512, see standard variant vs Nano variant.

For this reason, standard Libsodium libraries could generally not be used, such as the sodium_crypto_sign_publickey_from_secretkey() function proposed in the other answer. Apart from that, this function expects a 64 bytes key (consisting of seed and public key) while in Nano the private key is only 32 bytes (consisting of the seed).


The following example from the Nano documentation shows a private key, a public key and a public address:

"private": "781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3",
"public": "3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039",
"account": "nano_1e5aqegc1jb7qe964u4adzmcezyo6o146zb8hm6dft8tkp79za3sxwjym5rx" 

One way to get the public key with PHP is to use a library that supports Nano. Such a library is e.g. Salt, which also contains the Nano variant. With this library the determination of the public key is simply:

use MikeRow\Salt\NanoSalt;

$nanoSalt = new NanoSalt();
$public_key = $nanoSalt->crypto_sign_public_from_secret_key(hex2bin("781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3"));
print(strtoupper($public_key->toHex()) . PHP_EOL); // 3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039

Using the private key from the example results in the public key from the example.

Another way to get the public key would be to use a library that supports Ed25519 arithmetic, so that the public key can be obtained by multiplying by the base point. Such a library is e.g. phpseclib (although frankly I have not tested this way).


The public address is obtained by encoding the public key with a special Base32 variant and appending a checksum that is also Base32 encoded. The checksum is the Blake2b-40 hash of the public key, see here.

A library that supports the special Base32 variant and Blake2b is NanoPHP. Since the Blake2b implementation is a bit cumbersome, this Blake2b library can be used alternatively. A possible implementation is:

require "Uint.php";
require "Blake2b.php";

// publick key
$public_key = "3068bb1ca04525bb0e416c485fe6a67fd52540227d267cc8b6e8da958a7fa039";
$key = Uint::fromHex('0' . $public_key);
$key_base32 = $key->toString();
print($key_base32 . PHP_EOL);

// checksum
$blake40 = new Blake2b(5);
$hash = $blake40->hash(hex2bin($public_key));
$check = Uint::fromHex(bin2hex($hash))->reverse();
$check_base32 = $check->toString();
print($check_base32 . PHP_EOL);

print('nano_' . $key_base32 . $check_base32 . PHP_EOL); // nano_1e5aqegc1jb7qe964u4adzmcezyo6o146zb8hm6dft8tkp79za3sxwjym5rx

where Uint.php provides the Base32 encoding and comes from the NanoPHP library, while Blake2b.php is the more handy Blake2b alternative.

Using the public key from the example gives the correct address.


To test other private keys, this site is useful.


Regarding security: Be aware that all libraries used are rather small and may contain vulnerabilities.



Answered By - Topaco
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing