Theory Flashcards

1
Q

What is Blockchain

A

A blockchain is a distributed database that is shared among the nodes of a computer network.

A blockchain collects information together in groups, known as blocks, that hold sets of information. forming a chain of data known as the blockchain. Where transactions are recorded, and cannot be modified

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How Does a Blockchain Work?

A

https://www.investopedia.com/thmb/dERboL3dYS7NCsTY5NgB6b8thIQ=/750x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/dotdash_Final_Blockchain_Sep_2020-01-60f31a638c4944abbcfde92e1a408a30.jpg

In the case of the distributed network of blockchain architecture, each participant within the network maintains, approves, and updates new entries. The system is controlled not only by separate individuals, but by everyone within the blockchain network. Each member ensures that all records and procedures are in order, which results in data validity and security. Thus, parties that do not necessarily trust each other are able to reach a common consensus.

A hash is like a fingerprint (long record consisting of some digits and letters). Each block hash is generated with the help of a cryptographic hash algorithm (SHA 256). Consequently, this helps to identify each block in a blockchain structure easily. The moment a block is created, it automatically attaches a hash, while any changes made in a block affect the change of a hash too. Simply stated, hashes help to detect any changes in blocks.

The final element within the block is the hash from a previous block. This creates a chain of blocks and is the main element behind blockchain architecture’s security. As an example, block 45 points to block 46. The very first block in a chain is a bit special - all confirmed and validated blocks are derived from the genesis block.

Each new user (node) joining the peer-to-peer network of blockchain receives a full copy of the system. Once a new block is created, it is sent to each node within the blockchain system. Then, each node verifies the block and checks whether the information stated there is correct. If everything is alright, the block is added to the local blockchain in each node.

All the nodes inside a blockchain architecture create a consensus protocol. A consensus system is a set of network rules, and if everyone abides by them, they become self-enforced inside the blockchain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Is Blockchain Secure?

A

When everyone else cross-references their copies against each other, they would see this one copy stand out, and that hacker’s version of the chain would be cast away as illegitimate.

Due to the size of many cryptocurrency networks and how fast they are growing, the cost to pull off such a feat probably would be insurmountable. This would be not only extremely expensive but also likely fruitless. Doing such a thing would not go unnoticed, as network members would see such drastic alterations to the blockchain. The network members would then hard fork off to a new version of the chain that has not been affected. This would cause the attacked version of the token to plummet in value, making the attack ultimately pointless, as the bad actor has control of a worthless asset.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Tell about Merkletrees

A

Блоки в биткойн-блокчейне — это перманентно записываемые файлы, которые содержат информацию о проведенных пользователями транзакциях. Дополнительно каждый блок содержит Generation Transaction (или Coinbase Transaction) — это транзакция с информацией об адресе с наградой за решение блока, которая всегда стоит первой в списке.

Все транзакции в блоке представлены как строки в шестнадцатеричном формате (raw transaction format), которые хешируются для получения идентификаторов транзакций (txid). На их основе строится хеш блока, который учитывается последующим блоком, обеспечивая неизменяемость и связность реестра. Единое хеш-значение блока собирается при помощи дерева Меркла, концепция которого была запатентована Ральфом Мерклом (Ralph Charles Merkle) в 1979 году.

Дерево Меркла, или хеш-дерево, — это двоичное дерево, конечные узлы которого — это хеши транзакций, а внутренние вершины — результаты сложения значений связанных вершин.

Построение дерева происходит следующим образом:

Вычисляются хеши транзакций, размещенных в блоке: hash(L1), hash(L2), hash(L3) и так далее.
Вычисляются хеши от суммы хешей транзакций, например hash(hash(L1) + hash(L2)). Так как дерево Меркла является бинарным, то число элементов на каждой итерации должно быть четным. Поэтому если блок содержит нечетное количество транзакций, то последняя дублируется и складывается сама с собой: hash (hash(L3) + hash(L3)).
Далее, вновь вычисляются хеши от суммы хешей. Процесс повторяется, пока не будет получен единый хеш — корень дерева Меркла (merkle root). Он является криптографическим доказательством целостности блока (то есть того, что все транзакции находятся в заявленном порядке). Значение корня фиксируется в заголовке блока.

In bitcoin and other cryptocurrencies​, Merkletrees serve to encode blockchaindata more securely. Merkle tree is used to calculate block header hash. So every transaction is being hashed, then like in tree hashed transactions are summed, and those summs are summed with other transaction hash summs until there is one hash for the entire block

Merkle trees solve this problem by considerably reducing the amount of data that has to be maintained for verification purposes. They hash all the records in the ledger, which effectively separates the proof of data from the data itself. Users can verify individual blocks and can also check transactions by using hashes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Blockchain DLT

A

Desetralized Distributed ledger technology (DLT) is a digital system for recording the transactions in which the transactions and their details are recorded in multiple places at the same time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

IPFS

A

IPFS — это аналог торрент-трекера, в котором некоторое количество узлов (компьютеров) свободно делятся хранящимися на них файлами, таким образом распространяя их по всей сети с возможностью получения свободного доступа.

IPFS (InterPlanetary File System, «Межпланетная файловая система») — это гипермедийный протокол связи с открытым кодом, с помощью которого компьютерные узлы осуществляют хранение и распространение данных в единой распределенной файловой системе.

Ключевое отличие IPFS от существующего интернет-протокола HTTP в том, что доступ к данным осуществляется не по местоположению сайта, а напрямую по адресу его содержимого (файлу, документу, изображению, папке).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Коины и токены: в чем разница?

A

Coin (коин) – это монета блокчейна.
Token (токен) – это монета, которая создается в сети блокчейна

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Types of wallets

A

Hot and Cold Wallets
Custodial and Non-Custodial Wallets
https://crypto.com/university/crypto-wallets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Ассиметричное шифрование

A

Публичныйключ - это адрес кошелька
Приватный ключ - используется для подписи транзакций

Вместо одного кода в асимметричном шифровании или шифровании с открытым ключом используется пара ключей. В то время как отправитель шифрует сообщение открытым ключом, получатель использует свой закрытый ключ (также называемый секретным ключом) для его расшифровки.

Без закрытого ключа, даже если у кого-то есть соответствующий открытый ключ, невозможно расшифровать и прочитать сообщение отправителя.

Вот почему закрытый ключ должен храниться в секрете, так как предоставление его кому-то другому увеличивает риск несанкционированного доступа.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Hash functions in Blockchain

A

Хэш функции кодируют данные в блоках(хэш транзакции), которые потом с помошью дерева меркля образуют хэш блока

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Что делаают майнеры?

A

Все биткоин-переводы записываются в общедоступный лог транзакций. По цепочке они передаются майнерам, чья работа состоит в том, чтобы подобрать из миллионов комбинаций один-единственный хэш, подходящий ко всем новым транзакциям и секретному ключу, который и обеспечит майнеру получение награды в 25 биткоинов за раз. Множество «добытчиков» одновременно борются за награду, пытаясь первыми угадать хэш. Как только хэш угадан, блок со всеми транзакциями закрыт, майнеры переходят к следующему.
Хэш, который ищут майнеры состоит из хэша предыдущего блока, суммы хэшей транзакций за последние 10 минут и случайного числа, которое майнеры меняют, чтобы итоговый хэш удовлетворял условиям системы. Именно изменение этих условий и определяет сложность нахождения хэша, они изменяются раз в 2016 закрытых блоков и автоматически подбираются так, чтобы расчёт каждых 2016 блоков занимал 2 недели.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Процесс майнинга в сети блокчейн

A

Each block has a unique hash associated with it. It is always a 64-digit number, regardless of transaction data.
The mining process is therefore nothing but the execution of algorithms (SHA-256 hashing algorithm for bitcoin mining) to hash the block headers to a value below the target.

Validating and encoding the blockchain is referred to as mining. Mining involves the use of computers to run hashing algorithms to process the most recent block; the information that a user needs to mine is found in the block’s header. The cryptocurrency network sets a target value for this hash—called the target hash—and miners try to determine what this value is by testing out all possible values.
The block header contains the block version number, a timestamp, the hash used in the previous block, the hash of the Merkle Root, the nonce, and the target hash. The block is generated by taking the hash of the block contents, adding a random string of numbers (the nonce), and hashing the block again.
If the hash meets the requirement of the target, then the block is added to the blockchain. Cycling through solutions in order to guess the nonce is referred to as proof of work (PoW), and the miner who is able to find the value is awarded the block and paid in cryptocurrency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is ERC-20?

A

The ERC-20 introduces a standard for Fungible Tokens

ERC-20 стал руководством по созданию заменяемых токенов (ориг. Fungible Tokens) — идентичных токенов, которые можно обменивать друг на друга.

Однако, до появления ERC-20 существовала проблема совместимости между различными токенами, ведь каждый из них имел уникальный смарт-контракт. Иными словами, для того, чтобы биржа или кошелек могли поддерживать токен, его создателям каждый раз нужно было писать совершенно новый код.

Таким образом, поддержка растущего число токенов становилась все более проблематичной, занимая слишком много времени. Для решения этой проблемы и был создан стандартный протокол для всех токенов.

ERC-20 значительно упростил и унифицировал выпуск токенов в рамках одной сети. Этот стандарт наряду со смарт-контрактами стал универсальным способом создания и монетизации приложений, использующих блокчейн. Так Ethereum стал первой в истории блокчейн-платформо

These tokens are:

💻 Fungible - The code of each individual token is the same as any other, though transaction histories can be used to identify and separate out the tokens involved.
🛫 Transferable - They can be sent from one address to another.
⛏️ Fixed supply - A fixed number of tokens must be created so that developers cannot issue more tokens and raise the supply.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is ERC

A

Is a document that programmers use to write smart contracts on Ethereum Blockchain

The Ethereum community use EIP to review these documents, and developers may revise documents
This is how the document becomes an ERC

While there are several Ethereum standards. These ERC Ethereum standards are the most well-known and popular –

ERC - 20
ERC - 721
ERC - 1155
ERC - 777

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is ERC-721?

A

ERC-721 is a token standard on Ethereum for non-fungible tokens (NFTs). Fungible means interchangeable and replaceable; Bitcoin is fungible because any Bitcoin can replace any other Bitcoin. Each NFT, on the other hand, is completely unique. One NFT cannot replace another.

The main characteristic of ERC-721 tokens is that each one is unique. When an ERC-721 token is created, there is one and only one of those tokens in existence. These tokens, as NFTs, have spread the idea and application of unique assets on Ethereum.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is ERC-1155 ?

A

ERC-1155 - Ethereum’s Flexible Token Standard
https://hsto.org/r/w1560/webt/ky/18/am/ky18amnutzngsgxlzhuc_cd4jm8.png
ERC-1155 solves for this by combining the two token standards. ERC-1155 is a token standard that enables the efficient transfer of fungible and non-fungible tokens in a single transaction.

The initial motivation behind ERC-1155 was to address challenges faced by blockchain game developers and players.

Massively multiplayer online games (MMOs) contain tens of thousands of items—armor, weapons, shields, skins, coins, badges, castles, etc—that players can collect and trade with one another. Some items like coins are fungible while others like a sword are non-fungible. On the blockchain, each one of these items is a token.

Prior to ERC-1155, each item required its own smart contract. In a game with 100,000 items that means 100,000 smart contracts!

With an ERC-1155 token, multiple items can be stored in a single smart contract and any number of items can be sent in a single transaction to one or more recipients. This means if you wanted to send a sword to one friend, a shield to another, and 100 gold coins to both, you could do so in only one transaction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is ERC-777 ?

A

ERC-777

Этот формат является «усовершенствованием» привычного ERC-20. Он обратно совместим с ERC-20, но имеет несколько преимуществ:

при обмене токенов использует одну транзакцию вместо двух в ERC-20;
автоматически отменяет транзакции на несовместимые контракты;
возможность помечать неблагонадёжные адреса;
возможность назначать операторов (адреса, имеющие право отправлять токены с другого адреса);
ускоренное проведение транзакций.

18
Q

What is proxy?

A

When you create a new upgradeable contract instance, the OpenZeppelin Upgrades Plugins actually deploys three contracts:

The contract you have written, which is known as the implementation contract containing the logic.

A ProxyAdmin to be the admin of the proxy.

A proxy to the implementation contract, which is the contract that you actually interact with.

Here, the proxy is a simple contract that just delegates all calls to an implementation contract. A delegate call is similar to a regular call, except that all code is executed in the context of the caller, not of the callee. Because of this, a transfer in the implementation contract’s code will actually transfer the proxy’s balance, and any reads or writes to the contract storage will read or write from the proxy’s own storage.

This allows us to decouple a contract’s state and code: the proxy holds the state, while the implementation contract provides the code. And it also allows us to change the code by just having the proxy delegate to a different implementation contract.

An upgrade then involves the following steps:

Deploy the new implementation contract.

Send a transaction to the proxy that updates its implementation address to the new one.

Any user of the smart contract always interacts with the proxy, which never changes its address. This allows you to roll out an upgrade or fix a bug without requesting your users to change anything on their end - they just keep interacting with the same address as always.

19
Q

TESTING SMART CONTRACTS

A

AUTOMATED TESTING FOR SMART CONTRACTS
1. Functional testing
Functional testing verifies the functionality of a smart contract and provides assurance that each function in the code works as expected.
Functional testing covers three methods: unit testing, integration testing, and system testing.

Unit testing involves testing individual components in a smart contract for correctness. A unit test is simple, quick to run, and provides a clear idea of what went wrong if the test fails.

In integration testing, individual components of the smart contract are tested together. This approach detects errors arising from interactions between different components of a contract or across multiple contracts.

System testing is the final phase of functional testing for smart contracts. A good way to perform system testing on a smart contract is to deploy it on a production-like environment, such as a testnet or development network.

Static analysis

Static analysis examines the source code or bytecode of a smart contract before execution. This means you can debug contract code without actually running the program. Static analyzers can detect common vulnerabilities in Ethereum smart contracts and aid compliance with best practices.

Dynamic analysis

Dynamic analysis techniques require executing the smart contract in a runtime environment to identify issues in your code. Dynamic code analyzers observe contract behaviors during execution and generate a detailed report of identified vulnerabilities and property violations.

Fuzzing is an example of a dynamic analysis technique for testing contracts. During fuzz testing, a fuzzer feeds your smart contract with malformed and invalid data and monitors how the contract responds to those inputs.

MANUAL TESTING FOR SMART CONTRACTS
1. Code audits
2. Bug bounties

20
Q

What is Single Point of Failure?

A

A single point of failure is any part of a system that, if it fails, will stop the entire system from working.

The best way to avoid this is to reject depending on a single point entirely and has many distributed points.

Bitcoin blockchain is a decentralized network where transactions are stored and distributed across multiple nodes(servers). If a single node fails, the network does not go down and transactions won’t be lost.

21
Q

authorization and authentication

A

authentication is the process of verifying who someone is, whereas authorization is the process of verifying what specific applications, files, and data a user has access to

22
Q

False positive & true positive

A

Let’s make the following definitions:

“Wolf” is a positive class.
“No wolf” is a negative class.

True Positive (TP):
Reality: A wolf threatened.
Shepherd said: “Wolf.”
Outcome: Shepherd is a hero.
False Positive (FP):
Reality: No wolf threatened.
Shepherd said: “Wolf.”
Outcome: Villagers are angry at shepherd for waking them up.
False Negative (FN):
Reality: A wolf threatened.
Shepherd said: “No wolf.”
Outcome: The wolf ate all the sheep.
True Negative (TN):
Reality: No wolf threatened.
Shepherd said: “No wolf.”
Outcome: Everyone is fine.

https://developers.google.com/machine-learning/crash-course/classification/true-false-positive-negative

23
Q

what is proof of stake?

A

In a proof of stake system, staking serves a similar function to proof of work’s mining, in that it’s the process by which a network participant gets selected to add the latest batch of transactions to the blockchain and earn some crypto in exchange.

The exact details vary by project, but in general proof of stake blockchains employ a network of “validators” who contribute — or “stake” — their own crypto in exchange for a chance of getting to validate new transaction, update the blockchain, and earn a reward.

24
Q

Proof of History (PoH)?

A

Proof of Stake and Proof of History are quite similar. This is due to the fact that Proof of Stake evolved into Proof of History. Both algorithms are built on the same foundation. Validators are used in both algorithms to guarantee that transactions are validated and new blocks are created.
However, there is a significant difference between these two methods in terms of how time is calculated. The timestamp function is used in Proof of Stake. This means that each node relies on the network’s timestamp. Because time must flow via the network first, the network will operate slower.

This isn’t essential with Proof of History the time is calculated based on historical occurrences. After analyzing these occurrences, a hash function is constructed that can be confirmed by anybody. Every block created by the network has this hash appended to it. This method of determining the time takes essentially little time.

25
Q

Proof of Space and Time

A

‘Proof of Space and Time’ consensus mechanism that allows users to securely store important data with better security, speed and scalability than traditional cloud storage services.

26
Q

Impermanent loss

A

The loss is the difference between the value of the tokens had the provider simply held onto them, minus the value of the tokens after they were added to a pool and a volatile market reduced their value. The potential for loss stems from the fact that a liquidity provider must add an equal value of the two tokens in the liquidity pool.

27
Q

What is Defi?

A

DeFi (or “decentralized finance”) is term for financial services on public blockchains, primarily Ethereum. With DeFi, you can do most of the things that banks support — earn interest, borrow, lend, buy insurance, trade derivatives, trade assets, and more — but it’s faster and doesn’t require paperwork or a third party.

28
Q

What is Defi protocol?

A

DeFi protocols are simply codes, procedures, and rules which rules the systemss in DeFi. Through DeFi protocols, participants in the ecosystem are able to trade, lend, stake tokens, and much more. These protocols must be accessible to all wallets so that anyone participating in the DeFi system can follow the same set of rules.

29
Q

What is Falback function?

A

// This function is called for all messages sent to
// contract, except plain Ether transfers
// (there is no other function except the receive function).
// Any call with non-empty calldata to this contract will execute
// the fallback function (even if Ether is sent along with the call).

30
Q

tranfer, send, call

A

https://blockchain-academy.hs-mittweida.de/courses/solidity-coding-beginners-to-intermediate/lessons/solidity-2-sending-ether-receiving-ether-emitting-events/topic/sending-ether-send-vs-transfer-vs-call/

31
Q

Multiple Inheritance

A

https://consensys.github.io/smart-contract-best-practices/development-recommendations/solidity-specific/complex-inheritance/

32
Q

Assert to check Invariants

A

Assert is used to check invariants. Those are states our contract or variables should never reach, ever. For example, if we decrease a value then it should never get bigger, only smaller.

33
Q

What do overflow and underflow mean?

A

In simple words, overflow is a situation when uint (unsigned integer) reaches its byte size. Then the next element added will return the first variable element.

Let’s say we have a uint8, which can only have 8 bits. That means the largest number we can store is binary 11111111 (in decimal 2^8 - 1 = 255)

uint8 balance = 255;
balance++;

If you execute the code above the “balance” will be 0. This is a simple example of overflow. If you add 1 to binary 11111111, it resets back to 00000000.

In the case of underflow, if you subtract 1 from a uint8 that is 0, it will change the value to 255.

Now I show you a simple implementation of underflow in Solidity.

34
Q

Access Modifier

A

Public

The Public element can be inherited and can be accessed by external elements. All can access a public element.

Private

The Private element doesn’t get inherited and can’t be accessed by external elements. It can be accessed from the current contract instance only.

Internal

The Internal element can be inherited but can’t be accessed by external elements. Only the base contract and derived contract can access internal element.

External

The External element can’t be inherited but it can be accessed by external elements. Current contract instance can’t access external element, it can be accessed externally only.

35
Q

Calldata, storage, memory

A

Calldata is only valid for parameters of external contract functions and is required for this type of parameter. Calldata is a non-modifiable, non-persistent area where function arguments are stored, and behaves mostly like memory.

36
Q

Solidity Struct?

A

A struct is a creative data structure format in Solidity where variables of diverse data types can be bundled into one variable or a custom-made type

37
Q

Solidity Enums?

A

Enums restrict a variable to have one of only a few predefined values.

38
Q

Delegate Call

A

delegatecall is a low level function similar to call.

When contract A executes delegatecall to contract B, B’s code is executed

with contract A’s storage, msg.sender and msg.value.

39
Q

Data Location & Assignment:

A

Assignments between storage and memory (or from calldata) always create an independent copy.

Assignments from memory to memory only create references. This means that changes to one memory variable are also visible in all other memory variables that refer to the same data.

Assignments from storage to a local storage variable also only assign a reference.

All other assignments to storage always copy. Examples for this case are assignments to state variables or to members of local variables of storage struct type, even if the local variable itself is just a reference.

40
Q

Slippage

A

Slippage is defined as the percentage difference between the quoted price and executed price of a trade