Alyssa

masterServer

Dec 20th, 2017
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 20.55 KB | None | 0 0
  1. --Thanks to Valithor for the encryption and hashing API
  2. if fs.exists("/encrypt.lua") then
  3.     os.loadAPI("/encrypt.lua")
  4. else
  5.     shell.run("pastebin get cyiVcsMm /encrypt.lua")
  6.     os.loadAPI("/encrypt.lua")
  7. end
  8.  
  9. if fs.exists("/hash.lua") then
  10.     os.loadAPI("/hash.lua")
  11. else
  12.     shell.run("pastebin get fd9W1x9y /hash.lua")
  13.     os.loadAPI("/hash.lua")
  14. end
  15.  
  16. relay = peripheral.wrap("right")
  17. modem = peripheral.wrap("top")
  18.  
  19. sides = {bottom=0, top=1, back=2, front=3, right=4, left=5}
  20. alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}
  21.  
  22. vaultSides = {sides.top, sides.left, sides.right, sides.back, sides.front}
  23. debug = false
  24. extension = ".coin"
  25. boxExt = ".box"
  26. baseCoin = "gc"
  27. atmPort = 8374
  28. subKeyLength = 16
  29.  
  30. screenX, screenY = term.getSize()
  31. blank = string.rep(" ", screenX)
  32. if not debug then
  33.     input = window.create(term.native(), 1, screenY, screenX, 1)
  34.     info = window.create(term.native(), 1, 1, screenX, screenY-1)
  35.     term.clear()
  36.     term.redirect(input)
  37. end
  38.  
  39. --[[
  40. Console & Misc Functions
  41. --]]
  42.  
  43. function cPrint(txt)
  44.     if not debug then
  45.         term.redirect(info)
  46.         print(txt)
  47.         term.redirect(input)
  48.         term.setCursorPos(1,1)
  49.     else
  50.         print(txt)
  51.     end
  52. end
  53.  
  54. function worldTime()
  55.     return os.day() + (os.time() * (25/600))
  56. end
  57.  
  58. --[[
  59. Coin Functions
  60. --]]
  61.  
  62. function addCoin(coinName)
  63.     local f = fs.open("/bank/coins/" .. coinName .. extension, "w")
  64.     local coinData = {}
  65.     coinData["id"] = coinName
  66.     coinData["enabled"] = false
  67.     coinData["worth"] = 0
  68.     coinData["name"] = "Undefined Coin"
  69.     coinData["short"] = "uc"
  70.     coinData["material"] = "Undefined"
  71.     f.write(textutils.serialize(coinData))
  72.     f.close()
  73.     return coinData
  74. end
  75.  
  76. function getCoin(coinName)
  77.     local f = fs.open("/bank/coins/" .. coinName .. extension, "r")
  78.     local coinData = textutils.unserialize(f.readAll())
  79.     f.close()
  80.     return coinData
  81. end
  82.  
  83. function findCoin(coinDescription)
  84.     if coins[coinDescription:lower()] then
  85.         return coins[coinDescription:lower()]
  86.     end
  87.     for k, coinVal in pairs(coins) do
  88.         if coinVal["short"]:lower() == coinDescription:lower() then
  89.             return coinVal
  90.         elseif coinVal["material"]:lower() == coinDescription:lower() then
  91.             return coinVal
  92.         end
  93.     end
  94.     return false
  95. end
  96.  
  97. --[[
  98. Deposit Box Functions
  99. --]]
  100.  
  101. --KILL
  102. --ME
  103.  
  104. --[[
  105. Withdraw Box Functions
  106. --]]
  107.  
  108. function addWithdrawBox(boxUuid, side)
  109.     local f = fs.open("/bank/withdrawbox/" .. boxUuid .. tostring(side) .. boxExt, "w")
  110.     local boxData = {}
  111.     boxData["uuid"] = boxUuid
  112.     boxData["name"] = "Undefined Withdraw Box"
  113.     boxData["id"] = "UWB-1"
  114.     boxData["side"] = side
  115.     f.write(textutils.serialize(boxData))
  116.     f.close()
  117.     return boxData
  118. end
  119.  
  120. function getWithdrawBox(boxUuid)
  121.     local f = fs.open("/bank/withdrawbox/" .. boxUuid .. boxExt, "r")
  122.     local boxData = textutils.unserialize(f.readAll())
  123.     f.close()
  124.     return boxData
  125. end
  126.  
  127. function findWithdrawBox(boxDescription)
  128.     local boxDescription = boxDescription:lower()
  129.     if withdrawBoxes[boxDescription] then
  130.         return withdrawBoxes[boxDescription]
  131.     end
  132.     for _, boxVal in pairs(withdrawBoxes) do
  133.         if boxVal["id"]:lower() == boxDescription then
  134.             return boxVal
  135.         elseif boxVal["name"]:lower() == boxDescription then
  136.             return boxVal
  137.         end
  138.     end
  139.     return false
  140. end
  141.  
  142. --[[
  143. Coin Stock Functions
  144. --]]
  145.  
  146. function saveStock(stock)
  147.     local f = fs.open("/bank/stock.table","w")
  148.     f.write(textutils.serialize(stock))
  149.     f.close()
  150. end
  151.  
  152. --[[
  153. Communication / ATM Registry Functions
  154. --]]
  155.  
  156. function validATM(atmId)
  157.     for _, atm in atms do
  158.         if atm:lower() == atmId:lower() then
  159.             return true
  160.         end
  161.     end
  162.     return false
  163. end
  164.  
  165. function randomAlpha(length)
  166.     local txt = ""
  167.     for i = 1, length do
  168.         txt = txt .. alphabet[math.random(1,26)]
  169.     end
  170.     return txt
  171. end
  172.  
  173. --[[
  174. Bank User Functions
  175. --]]
  176.  
  177. function userExists(username)
  178.     return fs.exists("/bank/users/" .. username:lower())
  179. end
  180.  
  181. function createUser(username, password)
  182.     local username = username:lower()
  183.     if not userExists(username) then
  184.         fs.makeDir("/bank/users/" .. username)
  185.         local userPath = "/bank/users/" .. username .. "/"
  186.         local salt = randomAlpha(16)
  187.         local hashedPassword = hash.hash(password, salt)
  188.         local authInfo = {}
  189.         authInfo["password"] = hashedPassword
  190.         authInfo["salt"] = salt
  191.         authInfo["username"] = username
  192.         local f = fs.open(userPath .. "auth","w")
  193.         f.write(textutils.serialize(authInfo))
  194.         f.close()
  195.         local f = fs.open(userPath .. "balance","w")
  196.         f.write("0")
  197.         f.close()
  198.         return true
  199.     else
  200.         return false
  201.     end
  202. end
  203.  
  204. function removeUser(username)
  205.     if userExists(username) then
  206.         fs.delete("/bank/users/" .. username)
  207.         return true
  208.     else
  209.         return false
  210.     end
  211. end
  212.  
  213. function getBalance(username)
  214.     local username = username:lower()
  215.     if userExists(username) then
  216.         local f = fs.open("/bank/users/" .. username .. "/balance","r")
  217.         local balance = tonumber(f.readAll())
  218.         f.close()
  219.         return balance
  220.     end
  221.     return false
  222. end
  223.  
  224. function setBalance(username, newBalance)
  225.     local username = username:lower()
  226.     if userExists(username) then
  227.         local f = fs.open("/bank/users/" .. username .. "/balance","w")
  228.         f.write(tostring(newBalance))
  229.         f.close()
  230.         return newBalance
  231.     end
  232.     return false
  233. end
  234.  
  235. function addBalance(username, amount)
  236.     local username = username:lower()
  237.     local amount = tonumber(amount)
  238.     if userExists(username) then
  239.         local curBalance = getBalance(username)
  240.         local newBalance = curBalance + amount
  241.         return setBalance(username, newBalance)
  242.     end
  243.     return false
  244. end
  245.  
  246. function handleDeposit(atmId, username)
  247.     if userExists(username) then
  248.         local depBox = findDepositBox(atmId)
  249.         if depBox then
  250.             local depositItems = getAllStacks(depBox["uuid"], sides.top)
  251.             local chestSizeBelow = getInventorySize(depBox["uuid"], sides.bottom)
  252.             local chestSlot = 0
  253.             local careful = false
  254.             for i = #depositItems, 1, -1 do
  255.                 chestSlot = chestSlot + 1
  256.                 if chestSlot > chestSizeBelow then
  257.                     chestSlot = 1
  258.                     careful = true
  259.                 end
  260.                 if careful == true then
  261.                     while getStackInSlot(depBox["uuid"],sides.bottom,1) ~= nil do
  262.                         sleep(0.5)
  263.                     end
  264.                 end
  265.                 local coinData = depositItems[i]
  266.                 local coinName = coinData["name"]:gsub("%W","") .. coinData["damage"]
  267.                 if findCoin(coinName) then
  268.                     local coinObj = findCoin(coinName)
  269.                     transferItem(depBox["uuid"], sides.top, sides.bottom, coinData["size"], coinData["slot"], chestSlot)
  270.                     stock[coinName] = stock[coinName] + coinData["size"]
  271.                     addBalance(username, coinObj["worth"] * coinData["size"])
  272.                     saveStock(stock)
  273.                 end
  274.             end
  275.         end
  276.     end
  277. end
  278.  
  279. function handleWithdraw(atmId, username, withdrawCoins)
  280.     if userExists(username) then
  281.    
  282.     end
  283. end
  284.  
  285. --[[
  286. Transposer Functions
  287. --]]
  288.  
  289. function getInventorySize(uuid, side)
  290.     return relay.callRemote(uuid, "getInventorySize", side)
  291. end
  292.  
  293. function getAllStacks(uuid, side)
  294.     local nilStacks = 0
  295.     local maxNilStacks = 5
  296.     local stacks = {}
  297.     local maxStacks = getInventorySize(uuid, side)
  298.     for i = 1, maxStacks do
  299.         local curStack = getStackInSlot(uuid, side, i)
  300.         if curStack == nil then
  301.             nilStacks = nilStacks + 1
  302.             if nilStacks >= maxNilStacks then
  303.                 break
  304.             end
  305.         else
  306.             curStack["slot"] = i
  307.             table.insert(stacks, curStack)
  308.         end
  309.     end
  310.     return stacks
  311. end
  312.  
  313. function transferItem(uuid, source, sink, count, sourceSlot, sinkSlot)
  314.     return relay.callRemote(uuid, "transferItem", source, sink, count, sourceSlot, sinkSlot)
  315. end
  316.  
  317. function getStackInSlot(uuid, side, slot)
  318.     return relay.callRemote(uuid, "getStackInSlot", side, slot)
  319. end
  320.  
  321. --[[
  322. Initialization
  323. --]]
  324.  
  325. transposers = {}
  326. tVaults = {}
  327. tDeposits = {}
  328. tWithdraws = {}
  329.  
  330. for k, uuid in pairs(relay.getNamesRemote()) do
  331.     if relay.getTypeRemote(uuid) == "transposer" then
  332.         table.insert(transposers, uuid)
  333.         if getInventorySize(uuid, sides.bottom) and getInventorySize(uuid, sides.bottom) then
  334.             if not getInventorySize(uuid, sides.top) or getInventorySize(uuid, sides.top) < 5 then
  335.                 table.insert(tVaults, uuid)
  336.             else
  337.                 table.insert(tDeposits, uuid)
  338.             end
  339.         else
  340.             table.insert(tWithdraws, uuid)
  341.         end
  342.     end
  343. end
  344.  
  345. cPrint("Found " .. tostring(#tVaults) .. " tVaults")
  346. cPrint("Found " .. tostring(#tDeposits) .. " tDeposits")
  347. cPrint("Found " .. tostring(#tWithdraws) .. " tWithdraws")
  348.  
  349. vaults = {}
  350.  
  351. cPrint("Discovering coin storage...")
  352.  
  353. for k, transposer in pairs(tVaults) do
  354.     for kb, side in pairs(vaultSides) do
  355.         if getInventorySize(transposer, side) and getInventorySize(transposer, side) == 3 then
  356.             coinInfo = getStackInSlot(transposer, side, 3)
  357.             vaultInfo = {}
  358.             vaultInfo["transposer"] = transposer
  359.             vaultInfo["side"] = side
  360.             vaultInfo["coin"] = coinInfo["name"] .. "#" .. tostring(coinInfo["damage"])
  361.             table.insert(vaults, vaultInfo)
  362.         end
  363.     end
  364. end
  365.  
  366. cPrint("Found " .. tostring(#vaults) .. " coins.")
  367.  
  368. if not fs.exists("/bank") or not fs.isDir("/bank") then
  369.     if fs.exists("/bank") then
  370.         fs.delete("/bank")
  371.     end
  372.     fs.makeDir("/bank/")
  373.     cPrint("Created /bank")
  374. end
  375.  
  376. stock = {}
  377.  
  378. if not fs.exists("/bank/stock.table") or fs.isDir("/bank/stock.table") then
  379.     if fs.exists("/bank/stock.table") then
  380.         fs.remove("/bank/stock.table")
  381.     end
  382.     for k, coin in pairs(vaults) do
  383.         coinName = coin["coin"]:gsub("%W","")
  384.         stock[coinName] = 0
  385.     end
  386.     cPrint("Created stock table file.")
  387.     saveStock(stock)
  388. else
  389.     f = fs.open("/bank/stock.table","r")
  390.     stock = textutils.unserialize(f.readAll())
  391.     f.close()
  392.     cPrint("Loaded stock")
  393. end
  394.  
  395. if not fs.exists("/bank/coins") or not fs.isDir("/bank/coins") then
  396.     if fs.exists("/bank/coins") then
  397.         fs.delete("/bank/coins")
  398.     end
  399.     cPrint("Initializing coin directory...")
  400.     fs.makeDir("/bank/coins")
  401.     for _, coin in pairs(vaults) do
  402.         coinName = coin["coin"]:gsub("%W","")
  403.         addCoin(coinName)
  404.         stock[coinName] = 0
  405.     end
  406.     saveStock(stock)
  407. end
  408.  
  409. coins = {}
  410. cPrint("Loading coins...")
  411.  
  412. for _, coin in pairs(vaults) do
  413.     local coinName = coin["coin"]:gsub("%W","")
  414.     if not fs.exists("/bank/coins/" .. coinName .. extension) then
  415.         coins[coinName] = addCoin(coinName)
  416.         stock[coinName] = 0
  417.         saveStock(stock)
  418.         cPrint("Initialized missing coin " .. coinName)
  419.     else
  420.         coins[coinName] = getCoin(coinName)
  421.     end
  422. end
  423.  
  424. cPrint("Loaded coins")
  425.  
  426. if not fs.exists("/bank/depositbox/") or not fs.isDir("/bank/depositbox/") then
  427.     if fs.exists("/bank/depositbox/") then
  428.         fs.delete("/bank/depositbox/")
  429.     end
  430.     fs.makeDir("/bank/depositbox/")
  431.     cPrint("Made folder for deposit boxes!")
  432. end
  433.  
  434. depositBoxes = {}
  435. cPrint("Loading deposit boxes...")
  436.  
  437. if not fs.exists("/bank/withdrawbox/") or not fs.isDir("/bank/withdrawbox/") then
  438.     if fs.exists("/bank/withdrawbox/") then
  439.         fs.delete("/bank/withdrawbox/")
  440.     end
  441.     fs.makeDir("/bank/withdrawbox/")
  442. end
  443.  
  444. withdrawBoxes = {}
  445.  
  446. for _, tWithdraw in pairs(tWithdraws) do
  447.     for _, side in pairs(sides) do
  448.         if getInventorySize(tWithdraw, side) and getInventorySize(tWithdraw, side) > 54 then
  449.             if fs.exists("/bank/withdrawbox/" .. tWithdraw .. tostring(side)) then
  450.                 table.insert(withdrawBoxes, getWithdrawBox(tWithdraw, side))
  451.             else
  452.                 table.insert(withdrawBoxes, addWithdrawBox(tWithdraw, side))
  453.             end
  454.         end
  455.     end
  456. end
  457.  
  458. cPrint("Loaded withdraw boxes.")
  459.  
  460. atms = {}
  461.  
  462. if not fs.exists("/bank/atms.table") or fs.isDir("/bank/atms.table") then
  463.     if fs.exists("/bank/atms.table") then
  464.         fs.delete("/bank/atms.table")
  465.     end
  466.     f = fs.open("/bank/atms.table", "w")
  467.     f.write("{}")
  468.     f.close()
  469. else
  470.     f = fs.open("/bank/atms.table", "r")
  471.     atms = textutils.unserialize(f.readAll())
  472.     f.close()
  473. end
  474.  
  475. print("Loaded ATMs")
  476.  
  477. if not fs.exists("/bank/users") or not fs.isDir("/bank/users") then
  478.     if fs.exists("/bank/users") then
  479.         fs.delete("/bank/users")
  480.     end
  481.     fs.makeDir("/bank/users")
  482. end
  483.  
  484. print("Setting up server...")
  485. f = fs.open("/bank/atm.key","r")
  486. key = f.readAll()
  487. f.close()
  488. modem.open(atmPort)
  489.  
  490. cPrint("Initialization complete, starting server...")
  491.  
  492. --[[
  493. Console Commands
  494. --]]
  495.  
  496. commands = {}
  497.  
  498. commands["help"] = {func=function(args)
  499.     if args[2] then
  500.         if commands[args[2]] then
  501.             local helpText = commands[args[2]]["help"]
  502.             helpText = string.gsub(helpText, "%%CMD", args[2])
  503.             cPrint(helpText)
  504.         else
  505.             cPrint("Command not found.")
  506.         end
  507.     else
  508.         local commandList = ""
  509.         for k, v in pairs(commands) do
  510.             commandList = commandList .. k .. " | "
  511.         end
  512.         cPrint("Available commands: ")
  513.         cPrint(commandList)
  514.         cPrint("For help on a command, use help <cmd>")
  515.     end
  516. end, help="Usage: %CMD [CMD]"}
  517.  
  518. commands["coin"] = {func=function(args)
  519.     if args[2] then
  520.         if args[2] == "list" then
  521.             local coinList = ""
  522.             for k, v in pairs(coins) do
  523.                 coinList = coinList .. v["name"] .. " (" .. v["id"] .. ") | "
  524.             end
  525.             cPrint("Coins: " .. coinList)
  526.         elseif args[2] == "info" then
  527.             if args[3] then
  528.                 local coin = findCoin(args[3])
  529.                 if coin then
  530.                     cPrint(coin["name"])
  531.                     cPrint("Enabled: " .. tostring(coin["enabled"]))
  532.                     cPrint("Worth: " .. tostring(coin["worth"]) .. "gc")
  533.                     cPrint("Material: " .. tostring(coin["material"]))
  534.                     cPrint("Currency Code: " .. tostring(coin["short"]))
  535.                     cPrint("Id: " .. tostring(coin["id"]))
  536.                 else
  537.                     cPrint("Unknown coin, usage: info <coin id/material/code>")
  538.                 end
  539.             else
  540.                 cPrint("Invalid argument, usage: info <coin>")
  541.             end
  542.         else
  543.             cPrint("Invalid subcommand, valid subcommands: list, info")
  544.         end
  545.     else
  546.         cPrint("No subcommand, valid subcommands: list, info")
  547.     end
  548. end, help="Usage: %CMD <list | info>"}
  549.  
  550. commands["user"] = {func=function(args)
  551.     if args[2] then
  552.         if args[2] == "create" then
  553.             if args[3] and args[4] then
  554.                 tryCreate = createUser(args[3],args[4])
  555.                 cPrint("Create user " .. args[3] .. ": " .. tostring(tryCreate))
  556.             else
  557.                 cPrint("Usage: create <username> <password>")
  558.             end
  559.         elseif args[2] == "remove" then
  560.             if args[3] then
  561.                 tryRemove = removeUser(args[3])
  562.                 cPrint("Removed user " .. args[3] .. ": " .. tostring(tryRemove))
  563.             else
  564.                 cPrint("Usage: remove <username>")
  565.             end
  566.         elseif args[2] == "balance" then
  567.             if args[3] then
  568.                 if args[4] then
  569.                     if args[4] == "set" and tonumber(args[5]) then
  570.                         cPrint(args[3] .. "'s new balance: " .. tostring(setBalance(args[3], tonumber(args[5]))))
  571.                     elseif args[4] == "add" and tonumber(args[5]) then
  572.                         cPrint(args[3] .. "'s new balance: " .. tostring(addBalance(args[3], tonumber(args[5]))))
  573.                     else
  574.                         cPrint("Usage: balance <user> <set | add> <amount>")
  575.                     end
  576.                 else
  577.                     cPrint(args[3] .. "'s balance: " .. tostring(getBalance(args[3])))
  578.                 end
  579.             else
  580.                 cPrint("Usage: balance <user> [set | add]")
  581.             end
  582.         else
  583.             cPrint("Invalid subcommand, valid subcommands: create, remove, balance")
  584.         end
  585.     else
  586.         cPrint("No subcommand, valid subcommands: create, remove, balance")
  587.     end
  588. end, help="Usage: %CMD <create | remove | balance>"}
  589.  
  590. commands["test"] = {func=function(args)
  591.     if args[2] then
  592.         if args[2] == "deposit" then
  593.             if args[3] and args[4] then
  594.                 handleDeposit(args[3], args[4])
  595.             else
  596.                 cPrint("Usage: deposit <atmId> <username>")
  597.             end
  598.         else
  599.             cPrint("Invalid subcommand, valid subcommands: deposit")
  600.         end
  601.     else
  602.         cPrint("No subcommand, valid subcommands: deposit")
  603.     end
  604. end, help="Usage: %CMD <deposit>"}
  605.  
  606. function console()
  607.     --[[
  608.     Controls the console
  609.     --]]
  610.     while true do
  611.         if not debug then
  612.             term.redirect(input)
  613.         end
  614.         term.setCursorPos(1,1)
  615.         term.write(blank)
  616.         term.setCursorPos(1,1)
  617.         term.write("> ")
  618.         local cmd = read()
  619.         if cmd:lower() == "exit" then
  620.             break
  621.         else
  622.             local cArgs = {}
  623.             for arg in cmd:gmatch("%S+") do table.insert(cArgs, arg) end
  624.             if commands[cArgs[1]:lower()] then
  625.                 commands[cArgs[1]:lower()]["func"](cArgs)
  626.             end
  627.         end
  628.     end
  629.     return
  630. end
  631.  
  632. function server()
  633.     --[[
  634.     Controls the server / communications
  635.     --]]
  636.     local subKeys = {}
  637.     while true do
  638.         local e = { os.pullEvent("modem_message") }
  639.         if e[2] == "top" and e[3] == atmPort then
  640.             --Received ATM Message
  641.             if e[5] and e[5]["id"] and validATM(e[5]["id"]) and e[5]["msg"] and subKeys[e[5]["id"]] then
  642.                 --Valid ATM Message
  643.                 local atmId = e[5]["id"]
  644.                 local atmMessage = encrypt.decrypt(e[5]["msg"], key .. subKeys[atmId])
  645.                 if atmMessage:sub(1,1) == "{" and atmMessage:sub(#atmMessage, #atmMessage) == "}" then
  646.                     local newKey = randomAlpha(subKeyLength)
  647.                     atmMessage = textutils.unserialize(encrypt.decrypt(e[5]["msg"], key))
  648.                     if atmMessage["op"] then
  649.                         --atmMessage decoded & Valid
  650.                         local op = atmMessage["op"]
  651.                         if op == "deposit" then
  652.                             if atmMessage["user"] then
  653.                                 if userExists(atmMessage["user"]) then
  654.                                     handleDeposit(atmId, atmMessage["user"])
  655.                                     local respMsg = {newKey=newKey, success=true}
  656.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  657.                                     subKeys[atmId] = newKey
  658.                                     modem.transmit(atmPort, 200, {to=atmId, op="depositStarted", msg=encMsg})
  659.                                 else
  660.                                     local respMsg = {newKey=newKey, error="Invalid User."}
  661.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  662.                                     subKeys[atmId] = newKey
  663.                                     modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  664.                                 end
  665.                             else
  666.                                 local respMsg = {newKey=newKey, error="No user supplied."}
  667.                                 local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  668.                                 subKeys[atmId] = newKey
  669.                                 modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  670.                             end
  671.                         elseif op == "withdraw" then
  672.                             if atmMessage["user"] and userExists(atmMessage["user"]) then
  673.                                 if atmMessage["coins"] then
  674.                                     handleWithdraw(atmId, atmMessage["user"], atmMessage["coins"])
  675.                                     local respMsg = {newKey=newKey, success=true}
  676.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  677.                                     subKeys[atmId] = newKey
  678.                                     modem.transmit(atmPort, 200, {to=atmId, op="withdrawStarted", msg=encMsg})
  679.                                 else
  680.                                     local respMsg = {newKey=newKey, error="No coins specified."}
  681.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  682.                                     subKeys[atmId] = newKey
  683.                                     modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  684.                                 end
  685.                             else
  686.                                 local respMsg = {newKey=newKey, error="Invalid or missing user."}
  687.                                 local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  688.                                 subKeys[atmId] = newKey
  689.                                 modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  690.                             end
  691.                         elseif op == "newUser" then
  692.                             if atmMessage["username"] and atmMessage["password"] then
  693.                                 local username = atmMessage["username"]
  694.                                 local password = atmMessage["password"]
  695.                                 if createUser(username, password) then
  696.                                     local respMsg = {newKey=newKey, success=true, username=username}
  697.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  698.                                     subKeys[atmId] = newKey
  699.                                     modem.transmit(atmPort, 200, {to=atmId, op="accountCreated", msg=encMsg})
  700.                                 else
  701.                                     local respMsg = {newKey=newKey, error="Could not create account."}
  702.                                     local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  703.                                     subKeys[atmId] = newKey
  704.                                     modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  705.                                 end
  706.                             else
  707.                                 local respMsg = {newKey=newKey, error="Missing username or password..."}
  708.                                 local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  709.                                 subKeys[atmId] = newKey
  710.                                 modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  711.                             end
  712.                         else
  713.                             local respMsg = {newKey=newKey, error="Invalid operation!"}
  714.                             local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  715.                             subKeys[atmId] = newKey
  716.                             modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  717.                         end
  718.                     else
  719.                         --Message decoded, but not valid.
  720.                         local respMsg = {newKey=newKey, error="Invalid message"}
  721.                         local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. subKeys[atmId])
  722.                         subKeys[atmId] = newKey
  723.                         modem.transmit(atmPort, 400, {to=atmId, op="error", msg=encMsg})
  724.                     end
  725.                 else
  726.                     modem.transmit(atmPort, 400, {to=atmId, op="error", umsg={erorr="Decryption error"}})
  727.                     --Decryption error
  728.                 end
  729.             elseif e[5] and e[5]["id"] and e[5]["getKey"] then
  730.                 local atmId = e[5]["id"]
  731.                 subKeys[atmId] = randomAlpha(subKeyLength)
  732.                 local respMsg = {newKey=subKeys[atmId]}
  733.                 local encMsg = encrypt.encrypt(textutils.serialize(respMsg), key .. e[5]["getKey"])
  734.                 modem.transmit(atmPort,100, {to=atmId, op="newKey", msg=encMsg})
  735.             end
  736.         end
  737.     end
  738. end
  739.  
  740. parallel.waitForAny(console, server)
Advertisement
Add Comment
Please, Sign In to add comment