-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4.Ethereum blockchain
430 lines (291 loc) · 24.8 KB
/
4.Ethereum blockchain
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
💠️ Ethereum Blockchain 💠️
1. Uses aacount to transfer the money ,data ,message.
2. Account is originator and target of transaction.
3. Two types of accounts: Contract account (CA) ---- only for smart contracts.
The address of this account is determined from tjhe creators address + transaction nonce.
Externally Owned Account (EOA) ----- needed to participate in ehtereum.
The address of this account is the creators public key.
4.Transaction need fees to be paid and if balance of account is enough to pay fees only then it can do transaction.
5. Wei(fees are paid in wei) = 1 Ethereum = 10^18 wei.
6. Every 17 seconds new block is created.
7. Keyfiles are used to store private key encrypted by password.
8. Interactive users : which give password run time.
9. Non interactive users : which provide password thorugh a file.
10. Every miner gets a reward of 5 ethers.
11. There is no limit on number of ethers produced.
12. Every ethereum block does not hold fix number of transaction
13. The Public private key cryptography is used where in the public key is derived from the ECA (Elliptical Curve Algorithm) and then public key is hashed(Keccak256 hashing) and last 20 bytes are taken as address of account.But mostly internally public key is used by Ethereum algorithm.
Keystores :
Keystores are used to store keyfiles .
two types:
1.Standard : standard needs 256MB memory and 1 second processing on a modern CPU to access a key
More secure ans recommended.
2.Light : light needs 4MB memory and 100 millisecond processing on a modern CPU to access a key
Credentail generation : 1.Create a random private key (64 (hex) characters / 256 bits / 32 bytes)
2.Derive the public key from this private key (128 (hex) characters / 512 bits / 64 bytes)
3.Derive the address from this public key's hash. (40 (hex) characters / 160 bits / 20 bytes)
Ethereum account cointains :
nonce related to transactions.
amount of ethers in that account.
contract code
Storage.
Account Lifecycle has following points :
1.Creation
2.Deletion
3.Update
4.Export
5.Import
Exporting an account :
When exporting an existing account, the caller must supply both the current passphrase to decrypt the account, as well as an export passphrase to re-
encrypt it with before returning the key-file to the user.
Importing an account :
When importing a new account, the caller must supply both the encryption passphrase of the key-file being imported, as well as a new passhprase with
which to store the account. This is required to allow storing account with different credentials than used for moving them around.
Signing in to an account :
1.Single Signature : Where for every transaction you need to give password and address of account.
2.Multiple Signature : Unlock the account once only and sign all the transaction once and then again lock them.
Ethereum transaction contains: Receipt of transaction
Amount of Wei
Signature of sender authorizing it : signing happens with private key and hash of data to be signed.
Message
START GAS --- max computatinal steps the transaction is allowed.
Gas price --- fee the sender pays per computational step
Ethereum block contain : Block header
trasactions
runnerup block header.
Ehtereum full node contains:
Software needed for transaction initiati
mining
validation
block generation
smart contract execution
EVM
Ethereum Tokens :
Associated with the blockchain
Can we converted into currency
Gold certificates
shares
Loyaalty points.
Smart contract creates tokens and manage them in all aspects.
Send some ehter to smart contract to get tokens.
To keep trade between different smart contracts that build tokens (i.e. trade btn token-token) u need to write different code.
And collect tokens into wallet again different code is needed to be written.
💁️ INSTEAD
-ERC20 was proposed that allowed to do all such things and like an interface that implements 6 methos in ur code.
-Name of token
-symbol
-decimal
METHODS
-total suppy of tokens (max. tokens)
-balanceof (return how may tokens the given address has)
-transfer (transfer from the contract to user)
-transfer from (transfer from one user to another)
-approve (verifies that the contract has enough tokens to give to user)
-allowance (verifies that user has enough tokens to give to another user)
Meaasages : Only contract can send message to other contract or EOA.
They are like transactions in ethreum only originate through a contract.
they include :
The sender of the message (implicit)
The recipient of the message
The amount of ether to transfer alongside the message
An optional data field
A STARTGAS value
When a CALL or a DELEGATECALL instrurction is executed in a contract a message is been made to other contract.
Consensus : Memory based rather than cPU based proof of work.
Whenever the receipient address is null the ethereum considers it as a "new contract" and assigns it creator + nonce address.
Smart contarct output is stored in receipt.
Smart Contracts can be used in financial derivatives to insurance premiums, breach contracts, property law, credit enforcement, financial services, legal processes, and crowdfunding agreements.
1. Autonomy
2. Trust
3. Accuracy
4. Back up
5. Savings
////////////// Blockchain contains state hash and receipt hash /////////////////
States in ethreum :
everthuing is calculated through states.
APPLY(S,TX) -> S' or ERROR
APPLY({ Alice: $50, Bob: $50 },"send $20 from Alice to Bob") = { Alice: $30, Bob: $70 }
But:
APPLY({ Alice: $50, Bob: $50 },"send $70 from Alice to Bob") = ERROR
For each input in TX:
If the referenced UTXO is not in S, return an error.
If the provided signature does not match the owner of the UTXO, return an error.
If the sum of the denominations of all input UTXO is less than the sum of the denominations of all output UTXO, return an error.
Return S' with all input UTXO removed and all output UTXO added.
------------------- GAS P0INTS -------------------
ethereum price varies with market but gas points donot vary.
a transaction has to pay the gas points as well as fees to minor.Gas ponits are like internet fees and minor fees ae like website fees.
Gas points for a particular transaction are specified during minnig.
------------------ Gas points ? Gas price ------------ (is it different) == no not different
If provided gas gets finished in middle then every change id=s reverted to original.
In ethreum blockchain : each transaction has gaspoints.
Gas points are requiresto pay to the minor for that particular transaction
each block has
Gaslimit -- total gas that is available for a block.
Gas spent ------ actual amount of gas spent at thr completion of block creation.
When a block is created , it has a transaction fee specified and the base fee of three ether.
There are Ommers inside a ethreum blockchain who are minors who have also created the block but not won it.they are given a small percentage of gas points.
EVM : EVM has three storage areas
1. Storage :The contract's long-term storage, a key/value store. Unlike stack and memory, which reset after computation ends, storage persists for the long term.
2. Memory : an infinitely expandable byte array mainly maintained or given for a particular function of contract.
3. Stack : computation work is performed on stack
Instruction set :
1. Condidtional jump/unconditional jump
2. access block number , timestamp of block.
Contracts :
You can also destruct a contract after its work is done once.
Ethers sent to self distruct contract are lost .
So it is better to disable the contract instead.
Even if u self destruct your contract does not mean its deleted its restained in history and in other computers hard disk as well.
Ehtereum Homstead, Metropolis ,Sereniyt ??????????????????????????????????? ==== These are all ethereum releases/versions
👨🔧️👨🔧️👨🔧️ Tasks performed by a minor : 👨🔧️👨🔧️👨🔧️
Check if the transaction is well-formed (ie. has the right number of values), the signature is valid, and the nonce matches the nonce in the sender's account. If not, return an error.
Calculate the transaction fee as STARTGAS * GASPRICE, and determine the sending address from the signature. Subtract the fee from the sender's account balance and increment the sender's nonce. If there is not enough balance to spend, return an error.
Initialize GAS = STARTGAS, and take off a certain quantity of gas per byte to pay for the bytes in the transaction.
Transfer the transaction value from the sender's account to the receiving account. If the receiving account does not yet exist, create it. If the receiving account is a contract, run the contract's code either to completion or until the execution runs out of gas.
If the value transfer failed because the sender did not have enough money, or the code execution ran out of gas, revert all state changes except the payment of the fees, and add the fees to the miner's account.
Otherwise, refund the fees for all remaining gas to the sender, and send the fees paid for gas consumed to the miner.
If there is no account on receiver side then the total transaction fees are simply gas Prices*Total length of transaction. as the minor fees will not be paid due to no actual transaction taking
place but only the checking by minor is done.
Computatinal state (while EVM is running) :
== (block_state, transaction, message, code, memory, stack, pc, gas).
block_state contains all the accounts in the block, their balances and storage.
Maximum limit of computational steps are set in each transaction if exceeded it is reverted wiht fees being paid. (START GAS value)
Decentralized Storage :
IPFS (Interplanetray File System)
1.Allowing files to go distirbuted
2.Anyone can request for certain file and once file comes can check the hash whether its tampered or not.
3.IPFS object contains :
DAta === size-256kb
Link
multiple objects can be linked with one another.
if file>256kb then multiple obj are usedand are linked.
Drawback :
if node containing file is inactive then file is gone
So,solution:
1.Make that file to be available to some more users
2.Incentivize the nodes so Filecoin got created.
-Tranfer of file anywhere can take place and nodes can rent their space to others to store their file.
More application on ethereum in ethereum white paper.
Uncles in Ethereum :
1.These are blocks mined by other miners but little late.
2.These minors also get reward to mine the uncles.
3.the block that contains the uncle should lie between 2<= block <=7.
4.For every uncle U in block B, the miner of B gets an additional 3.125% added to its coinbase reward and the miner of U gets 93.75% of a standard coinbase reward.
💨️💨️💨️💨️ GAS
In bitcoin the trnsaction fee is decided by length of the code or transaction.
But in ethereum the amount of work done in performing that operation is taken into consideration.
🔗️🔗️🔗️🔗️ Link for all gas for oprerations : https://docs.google.com/spreadsheets/d/1m89CVujrQe5LAFJ8-YAUCcNK950dUzMQPMJBxRtGCqs/edit?usp=sharing
1.For every 256 bits of data 6 gas is needed.
2.To perfrom Keccak256 hasing or evaluate it 30 gas is needed.
3.The price of one unit of gas is decided by the miners, currently it is around 5 to 21 GWei (One GWei is 10^9 Wei or 10^-9 Ether).
4.You are free to specify a gasprice, or keep the suggest one.
5.we issue Ether whose value is supposed to vary, but also implement a Gas Price in terms of Ether. If the price of Ether goes up, the Gas Price in terms of Ether should go down to keep the real cost
of Gas the same.
6.Gas Cost is a static value for how much a computation costs in terms of Gas, and the intent is that the real value of the Gas never changes, so this cost should always stay stable over time.
7.Gas Price is how much Gas costs in terms of another currency or token like Ether. To stabilise the value of gas, the Gas Price is a floating value such that if the cost of tokens or currency fluctuates, the Gas Price changes to keep the same real value. The Gas Price is set by the equilibrium price of how much users are willing to spend, and how much processing nodes are willing to accept.
8.Gas Limit is the maximum amount of Gas that can be used per block, it is considered the maximum computational load, transaction volume, or block size of a block, and miners can slowly change this value over time.
9.Gas Fee is effectively the amount of Gas needed to be paid to run a particular transaction or program (called a contract). The Gas Fees of a block can be used to imply the computational load, transaction volume, or size of a block. The gas fees are paid to the miners (or bonded contractors in PoS).
🔴️ Negative GAs Concept :
1. Whenever a user wants to clear the contract storage or want to delete the contract a negative gas concept is used.
2. Where in for ever contract clearing user gets 24000 gas refund and for storgae clearing user gets 15000 gas refund.
3. Such transactions are kept in refund counter.
4. But the total maximum refund can only be half of the gas provided.
5. Eg: you provide 60000 gas and two contract deletion so total is 48000 refund but still you get 30,000 only due to criteria
[ 1 ] A transaction with too little fuel will not even reach miners, regardless of the fee supplied.
[ 2 ] If adequate fuel is provided for a transaction, but the fee is too low, even though the transaction may reach miners, upon examining the transaction miners will not perform any computation.
[ 3 ] A low fuel transaction implies that it will use little computation or storage resources of the EVM, or that at runtime it will hit an Out of Gas exception and be reverted.
[4, 5, 6] Fees determine the order in which transactions will be included in the blockchain.
[ 7 ] The reason why providing high fuel can lead to a transaction taking longer to get mined is discussed in the section Potential delays with high startGas.
====================== Receipts =============
contain hash of final state
logs : logs contains 4 topics at max and data . u can search particular log by their topic
cumulative gas used
=================== ORACLES ===========================
They allow external data to get stored into the contract just like adding externla depedencies into android studio.
Process : you register with their contract and define a function they should call
their contract is read by an external entity, that sees your "query"
the external entity executes the query (eg. calling random.org)
calls your callback function either directly or through their contract
profit ;-)
when u want to include oracle in ur contract it creates its own directory fot that
├── caller
│ ├── contracts
│ ├── migrations
│ ├── test
│ └── truffle-config.js
├── oracle
│ ├── contracts
│ ├── migrations
│ ├── test
│ └── truffle-config.js
└── package.json
more on oracles in solidty file
************* MetaMask ******************
Metamask is a browser that interacts with blockchain network. Basically u can inteact with ur blockchain with the help of ur browser through metamask
It allows u to contact the blockchain even without having entire full node with u
************* Web3.js ***********************
It is a library that help nodes to interact with entire blockchain by javascript functions.
Connecting to ethereum node provider, interaction with blockchain ,providing account address from provider are some of the functions of web3.js
OR u can use command line interface to do so
what is geth????
Geth is a command line interface written in go language that allows you to run and operate a full ethereum node
You can deploy smart contract,transfer funds, mine blocks, generate ethers, check block history,create accounts
It is used to also create your own private network and connect to public mainnet.
You can fully test your appliaction before deploying to mainnet
commands for ethereum blockchain ::
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt install ethereum
$$$$$$$$$$$$$$$$$$$ DAPPs $$$$$$$$$$$$$$$$$$$$$$$
1.Ethereum API : ethereum apis are useful for interacting with etherum blockchain from user side. Eg - miner.start()
Management API - admin,miner,personal,txpool
Web3 API - web3,eth,net
for new account : personal.newAccount()
for view your balance : eth.viewBalance()
to see nodes connected to network : admin.peers()
Truffle : IDE for complete testing,deploying dapp on test network n all
migrations.js : help for deplyment of our contract
keeps track of changes
test.js : contains both solidity and js test enviromnent
truffle.js/truffle-config.js : We can define different development environments like testrpc,our own local host,etc which tells truffle where we r connecting our contract.
bs-config.js : this is configuration file for lite server.It allows u to override the default lite server config.(bc - browsersync as lite is built uopn bs server)
package.json : it is also used for defining project properties, description, author & license information, scripts, apart from dependencies
records the minimum version you app needs. If you update the versions of a particular package, the change is not going to be reflected here.
Created when u run npm init.
package-lock.json : Records the exact version of each installed package which allows you to re-install them. Future installs will be able to build an identical dependency tree.
Not compulsary to be in a project .
This is soley used to lock dependencies to a specific version number.
lite-server in npm : Lightweight development only node server that serves a web app, opens it in the browser, refreshes when html or javascript change, injects CSS changes using sockets, and
has a fallback page when a route is not found.
Ethereum metropolis : proof of work but is not energy based instead its memory based
ethereum constantinople : thinking to switch to proof of stake
where miner is selected based on stake he has
min stake to become a validator is 32 ethers and one wiht max stake is choosen
miner fee is selected based on transaction fees in pos
To avoid monopoly by the node with most stake, an age based round robin policy is used in addition to the basic POS. ?????//
one drawback is when u have nothing at stake so alternative is casper protocol
so if u have 3% of bitcoin or altcoin then u can mine 3% of blocks
so inorder to do 51% attack u need 51% of altcoin on POS
Casper : once u have made a block prepared with 2/3 of minors or validators putting in stake and its validated from among one then it has to be bet upon by
2/3 of validators and block gets accepted
PBFT (Practical byzentine fault tolerance) :
nodes vote to elect a leader and that leader adds next block
f = number of faulty nodes
3f + 1 = number of total nodes 2f+1 = number of validating nodes
step1 : a proposed leader takes transacrions from the pool and then form a block.SO the block is now pre-prepared
step2 : the pre-prepared block is then validated and all of them wait until 2f+1 validations are made and then block is prepared
Step3 : prepared block is then commited to the chain.So they shld have 2f+1 commit msggs
mainly used in hyperledger
=============== PRIVATE ETHEREUM BLOCKCHAIN ===============
1. As ethereum is public and transparent private firms cannot manage their transactions on ethereum
2. So this concept of private Ethereum came into picture where POA concept is used
3. POA is basically where some nodes are given authority to validate blocks and they can control censorship in bc
4. So private blockchain is maily used by banks and some private frims
5. In this u have to connect your on peers to the network and continue choose validators
6. Here other nodes keep a watch on validaters so that they do not tend to include any malicious block into the blokchain and validators keep watch on each others also
🔴️ Transaction Signing :
In general how a verification thru signature can happen of particular data :
SO When you want to verify if an address 'x' has signed msg 'y' or not, you just need .recover(y) function of webjs which returns an address and just check if 'x' == address returned.
The signed msg of the transaction contains v,r,s. These are used to get the public key of sender of transaction