I am using testrpc and web3.
I used the idiom below to ensure that only a previously defined user should be able to do something:
function doSomethingProtected() {
if ( msg.sender != authorizedUser )
throw;
flagSomething = true;
}
When calling the function on an instantiated contract with web3 as follows:
myContract.doSomethingProtected( { from: "0x..." } );
it worked. At first I was pleased but then I realized the web3 API had not required me to provide any passphrase for a private key or such like.
Can anyone with the simple knowledge of someones public key/address call this function?
The use of this idiom in the examples led me to believe a benefit of the Ethereum contracts was that it ensured msg.sender was cryptographically assured.
The reason is that you are using testRPC, which doesn't lock it's accounts, so you don't need a password.
If you were to do this with geth, you would need to unlock the account before sending from it.
Without the private key, that function will throw an error, so you are correct in using that authorization method.
It's difficult to be certain without seeing more of your code, but it seems likely that you were calling the contract on your local node, rather than sending a transaction. Transactions can only be signed by someone with the account's private key, meaning you can rely on msg.sender to be accurate, but messages executed on your local node won't enforce that. Any changes they make are rolled back and not applied to state, though, so it doesn't matter what your local call does.
In general, there are two ways to call a function from web3.js: Using a transaction or just using a "call". Only in transactions you can actually modify the blockchain content (reading is always possible). Transactions always require a valid signature and thus access to a private key.
The reason you were not asked for a password might be that you already unlocked the account. Furthermore, users other than the authorized user can call the function, only the changes will be thrown away.
My guess is that your account was already unlocked when calling the function. I don't remember the exact period that your account is unlocked after unlocking it in web3. I might be wrong though. Would have added this as a comment, but I am not allowed right now.
Related
On the ethers documentation, it says that the two most commons signers are:
Wallet, which is a class which knows its private key and can execute any operations with it.
JsonRpcSigner, which is connected to a JsonRpcProvider (or sub-class) and is acquired using getSigner
What I'm having trouble understanding is how a JsonRpcSigner is created when the provider is a web3provider (i.e., MetaMask). Doesn't a web3provider know its private key and should therefore return a Wallet when provider.getSigner() is run?
The Wallet singer is used when your ethers.js instance knows the private key directly.
Since MetaMask doesn't share the key with other applications, ethers.js uses the JsonRpcSigner to be able to request the local MetaMask instance over its API to sign the transaction when needed, and then receive the signed transaction back, without ethers.js ever knowing the key.
I think the Wallet subclass of abstract signer has both the sign and signMessage methods, but JsonRpcSigner (what you get from provider.getSigner()) does not. The use case is I'm trying to sign a transaction using sign from metamask for instance and then submit it later.
I'm working on something, just a proof of concept, where people are rewarded for sharing metadata about their IP location. In this case (please ignore the code errors for now), someone would submit their ip, I would send it to an oracle that would resolve it and send back metadata about the ip, then would send the address and metadata to another contract.
This is the naive attempt at pseudo code (or non-compiling, at least) I've come up with:
pragma solidity ^0.4.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract IpMeta is usingOraclize {
uint public metadata;
function Metadata(bytes32 _ipAddress) public {
update(_ipAddress);
}
function __callback(bytes32 myid, string result) public {
if (msg.sender != oraclize_cbAddress()) revert();
bytes32 ipMetadata = result;
/* send address and result to another contract */
}
function update(bytes32 ipAddress) public payable {
oraclize_query("URL", "xml(https://ipresolver.com?ipresolve=" . ipAddress . ")");
}
}
The goal here is to allow people to prove something about their IP address (country, provider, etc) without the actual IP address being stored with the wallet address in the transaction or anywhere else. Is there a way to hide input data? I'm at a loss on research, and it seems like it would be a really useful function if possible. The im/practicalities of anything other than how to keep input data hidden or inaccessible aren't important.
Thanks,
Mark
The EVM is essentially a network composed of nodes of computers. Anyone can run their own node and your smart contract code will get run on those computers if they have a valid node that can receive the transactions. And since the data will also get transmitted to those computers, the owner that sees the code running in his/her computer will eventually have the power to look into the process getting run(by overseeing network, inspecting memory, etc.).
So from my understanding, the difficulty of doing this depends on the implementation of a Ethereum node. Actually Ethereum's protocols handles some level of security by encrypting the p2p connection. However, what makes all these obsolete in your context is that, the input data is serviced and revealed by services like etherscan(random example). I think it's still possible to achieve want you want, but it will only be a workaround and it will be difficult.
I think of Ethereum and its EVM as a transparent computer, basically the data it receives and sends are not secure at all. If you want to achieve security, that's the thing to achieve in somewhere else, for example process the ip related jobs in some other secure place(trusted 3rd party), then store the data without ip onto the blockchain. That's the best I can think of.
I just started learning solidity and have some questiones about the smart contract I created for pratice/fun.
Please let me know if any of my concepts are inaccurate, appreciate for all the advices and suggestiones.
Description:
the concept of this smart contract is really simple, whoever send the bigger amount of ether into the contract wins, it will pair you with whoever is before you (if no one is before you, you are player_one) and it will reset after 2 player are played (so it can be played again)
Code:
contract zero_one {
address public player_one;
address public player_two;
uint public player_one_amount;
uint public player_two_amount;
function zero_one() public{
reset();
}
function play() public payable{
//Scenario #1 Already have two player in game, dont accpet new player. do I even need this check at all? since smart contract execute serially i should never face this condition?
if(player_one != address(0) && player_two != address(0)) throw;
//Scenario #2 First player enter the game
else if(player_one == address(0) && player_two == address(0)){
player_one=msg.sender;
player_one_amount = msg.value;
}
//Scenario #3 Second player join in, execute the game
else{
player_two = msg.sender;
player_two_amount = msg.value;
//check the amount send from player_one and player two, whoever has the bigger amount win and get their money
if(player_two_amount>player_one_amount){
player_one.transfer(player_one_amount+player_two_amount);
reset();
}
else if(player_two_amount<player_one_amount){
player_two.transfer(player_one_amount+player_two_amount);
reset();
}
else{
//return fund back to both player
player_one.transfer(player_one_amount);
player_two.transfer(player_two_amount);
reset();
}
}
}
function reset() internal{
player_one = address(0);
player_two = address(0);
player_one_amount = 0;
player_two_amount = 0;
}
}
Questions
When sending ether back to users, do I need to calcualate how much
gas is going to take? or would smart contract automatically deduct
the gas from the amount i am going to send
Is it correct to set reset() as interal since i only want it to be
called within the smart contract, it shouldn't be called by anyone else
Would Scenario#1 ever happen? since from what I understand
smart contract do not have to worry about race condition and it
should never be in that state?
Is adding playable to play correct? ( since user are going to send ether with this call)
Is using throw a bad practice? (warning on remix)
transfer vs send, why is it better to use transfer?
I coded this smart contract as a practice. I can already see that if
someone want to game the system, he could just wait for someone to be player_one and check the amount player_one send(after the block is mined) and just send a bigger sum than that. Is there anyway this exploit could be stopped? Is there other security/flaws I did not see?
Thanks!
When sending ether back to users, do I need to calcualate how much gas
is going to take? or would smart contract automatically deduct the gas
from the amount i am going to send
The gas limit specified when executing a transaction needs to cover all activity end-to-end. This includes calls out to other contracts, transfers, etc. Any gas not used after the transaction is mined is returned to you.
Is it correct to set reset() as interal since i only want it to be
called within the smart contract, it shouldn't be called by anyone
else
internal is fine for what you're intending to do. But, it's more like protected access. A sub-contract can call internal methods. private provides the strictest visibility.
Would Scenario#1 ever happen? since from what I understand smart
contract do not have to worry about race condition and it should never
be in that state?
No, it should not happen. You are correct that transactions are processed serially, so you don't really have to worry about race conditions. That doesn't mean you shouldn't have this sort of protection in your code though...
Is adding playable to play correct? ( since user are going to send
ether with this call)
Yes. Any method that is expecting to receive wei and uses msg.value needs to be marked as payable.
Is using throw a bad practice? (warning on remix)
throw is deprecated. You want to use one of revert, require, assert as of 0.4.13. The one you use depends on the type of check you're doing and if gas should be refunded. See this for more details.
transfer vs send, why is it better to use transfer?
send and transfer are similar. The difference is that send limited the amount of gas sent to the call, so if the receiving contract tried to execute any logic, it would most likely run out of gas and fail. In addition, failures during send would not propagate the error and simply return false. Source
I coded this smart contract as a practice. I can already see that if
someone want to game the system, he could just wait for someone to be
player_one and check the amount player_one send(after the block is
mined) and just send a bigger sum than that. Is there anyway this
exploit could be stopped? Is there other security/flaws I did not see?
Security is a much more in depth topic. Any data sent in a transaction is visible, so you can't hide the exploit you mentioned unless you use a private blockchain. You can encrypt data sent in a transaction yourself, but I don't believe you can encrypt sending ether.
In terms of other security issues, there are several tools out there that perform security checks on contracts. I'd suggest looking into one of those. Also, read through the security considerations page on the Solidity documentation.
I am using testrpc and truffle to test my smart contract before deploying it to the real network.
In my contract, each node has to register in the contract by calling the function register, after that he can send or receive messages to/from contract( the blockchain )
The problem is, when an address ( let say account 1 from testrpc accounts) call the functions (send or receive ) the transaction doesn't occur and this message appears
VM Exception while processing transaction: invalid JUMP at
But when I use another unregistered account to call this function, it works.
Although no messages have been sent or received but no exceptions..
Any idea how I can solve this.
Thanks
Unless your using an old version of solc to compile your solidity the chance of this being an optimization problem is almost none.
Now, what does this mean then, it can happen when for example you run a modifier and it doesn't work. or if you try to call a function you are not allowed to and it throws. For example, it happens a lot after an ICO finishes and you try to use a function that can't be used anymore due to a date constraint it returns an Invalid Jump
I can't see your code but I think you might have reversed your if condition in your modifier and now it returns true if the user is not registered.
An address in Solidity can be an account or a contract (or other things, such as a transaction). When I have a variable x, holding an address, how can I test if it is a contract or not?
(Yes, I've read the chapter on types in the doc)
Yes you can, by using some EVM assembly code to get the address' code size:
function isContract(address addr) returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
The top-voted answer with the isContract function that uses EXTCODESIZE was discovered to be hackable.
The function will return false if it is invoked from a contract's constructor (because the contract has not been deployed yet).
The code should be used very carefully, if at all, to avoid security hacks such as:
https://www.reddit.com/r/ethereum/comments/916xni/how_to_pwn_fomo3d_a_beginners_guide (archive)
To repeat:
Do not use the EXTCODESIZE check to prevent smart contracts from calling a function. This is not foolproof, it can be subverted by a constructor call, due to the fact that while the constructor is running, EXTCODESIZE for that address returns 0.
See sample code for a contract that tricks EXTCODESIZE to return 0.
Checking if a caller is a contract
If you want to make sure that an EOA is calling your contract, a simple way is require(msg.sender == tx.origin). However, preventing a contract is an anti-pattern with security and interoperability considerations.
require(msg.sender == tx.origin) will need revisiting when account abstraction is implemented.
Checking if a callee is a contract
As #Luke points out in a comment, there is no general on-chain way to find out about a callee. If you want to "call" an address, there's no general way to find out if that address is a contract, EOA, or an address that a new contract can be deployed on, or if it's a CREATE2 address.
One non-general way that works for some callees: you can have a mapping on-chain that stores addresses of known EOAs or contracts. (Just remember that for an address without any on-chain history, you can't know if it's an EOA or an address that a contract can be deployed on.)
This isn't something you can query from within a contract using Solidity, but if you were just wanting to know whether an address holds contract code or not, you can check using your geth console or similar with eg:
> eth.getCode("0xbfb2e296d9cf3e593e79981235aed29ab9984c0f")
with the hex string (here 0xbfb2e296d9cf3e593e79981235aed29ab9984c0f) as the address you wish to query. This will return the bytecode stored at that address.
You can also use a blockchain scanner to find the source code of the contract at that address, for example the ecsol library as shown on etherscan.io.
Edit: Solidity has changed since this answer was first written, #manuel-aráoz has the correct answer.
There is no way in solidity to check if an address is a contract. One of the goals of Ethereum is for humans and smart contracts to both be treated equally. This leads into a future where smart contracts interact seamlessly with humans and other contracts. It might change in the future , but for now an arbitrary address is ambiguous.
If you want to use nodejs to confirm, you can do this:
const Web3 = require('web3')
// make sure you are running geth locally
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
is_contract = async function(address) {
res = await web3.eth.getCode(address)
return res.length > 5
}
is_contract('your address').then(console.log)
From openzeppeling Address.sol library, it has this function:
pragma solidity ^0.8.1;
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
isContract will return false for the following types of addresses:
an externally-owned account
a contract in construction
an address where a contract will be created
an address where a contract lived, but was destroyed
What you can do, granted you have the information at hand.
If the transactions sender address was null or unoccupied then you can tell if the address is a contract account or an EOA (externally owned account).
i.e. when sending a create contract transaction on the network then the receive address in the transaction is null/not used.
Reference from github:
https://github.com/ethereum/go-ethereum/wiki/Contracts-and-Transactions
Hope this helps.
If you are checking whether the caller is an EOA rather than a contract:
Short answer:
require(tx.origin == msg.sender);
tx.origin is a reference of the original address who initiates this serial function call, while msg.sender is the address who directly calls the target function. Which means, tx.origin must be a human, msg.sender can be a contract or human. Thus, if someone calls you from a contract, then the msg.sender is a contract address which is different from tx.origin.
I know most contracts may use #Manuel Aráoz's code, which works in most cases. But if you call a function within the constructor of a contract, extcodesize will return 0 which fails the isContract check.
NOTE: DON'T use tx.origin under other circumstances if you are not clear about what it represents because .