fork(2) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <ctime>
  5. #include <sstream>
  6.  
  7. // Определение структуры блока
  8. struct Block {
  9. int index;
  10. time_t timestamp;
  11. std::string data;
  12. std::string prevHash;
  13. std::string hash;
  14.  
  15. Block(int idx, const std::string& dat, const std::string& prev)
  16. : index(idx), data(dat), prevHash(prev) {
  17. timestamp = time(nullptr);
  18. hash = calculateHash();
  19. }
  20.  
  21. // Функция для вычисления хеша (упрощенная)
  22. std::string calculateHash() {
  23. std::stringstream ss;
  24. ss << index << timestamp << data << prevHash;
  25. // Для реальных систем здесь используется более надежный хеш-алгоритм,
  26. // такой как SHA-256
  27. return std::to_string(std::hash<std::string>{}(ss.str()));
  28. }
  29. };
  30.  
  31. // Определение структуры блокчейна
  32. class Blockchain {
  33. public:
  34. std::vector<Block> chain;
  35.  
  36. Blockchain() {
  37. // Создание генезис-блока (первого блока)
  38. chain.push_back(createGenesisBlock());
  39. }
  40.  
  41. // Создание генезис-блока
  42. Block createGenesisBlock() {
  43. return Block(0, "Genesis Block", "0");
  44. }
  45.  
  46. // Получение последнего блока в цепочке
  47. Block getLastBlock() const {
  48. return chain.back();
  49. }
  50.  
  51. // Добавление нового блока в цепочку
  52. void addBlock(const Block& newBlock) {
  53. // Проверка предыдущего хеша
  54. if (newBlock.prevHash == getLastBlock().hash) {
  55. chain.push_back(newBlock);
  56. } else {
  57. std::cerr << "Ошибка: Хеш предыдущего блока не совпадает!" << std::endl;
  58. }
  59. }
  60.  
  61. private:
  62. // Дополнительный класс для хеширования
  63. std::hash<std::string> hasher;
  64. };
  65.  
  66. int main() {
  67. Blockchain myChain;
  68.  
  69. // Добавление новых блоков
  70. myChain.addBlock(Block(1, "Первая транзакция", myChain.getLastBlock().hash));
  71. myChain.addBlock(Block(2, "Вторая транзакция", myChain.getLastBlock().hash));
  72.  
  73. // Вывод информации о блоках (для примера)
  74. for (const auto& block : myChain.chain) {
  75. std::cout << "Block #" << block.index << ":" << std::endl;
  76. std::cout << " Data: " << block.data << std::endl;
  77. std::cout << " Hash: " << block.hash << std::endl;
  78. std::cout << " Previous Hash: " << block.prevHash << std::endl;
  79. std::cout << std::endl;
  80. }
  81.  
  82. return 0;
  83. }
  84.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Block #0:
  Data: Genesis Block
  Hash: 3462571104061657675
  Previous Hash: 0

Block #1:
  Data: Первая транзакция
  Hash: 10411059740331514875
  Previous Hash: 3462571104061657675

Block #2:
  Data: Вторая транзакция
  Hash: 17867362421039862109
  Previous Hash: 10411059740331514875