I discussed this at length yesterday and today in the Spacechains telegram group. The consensus seems to be that it was already known that for loops were possible and this particular implementation of them is extremely inefficient. A more efficient way to do an operation multiple times within a bounded range is to simply write it out as many times as you want to run it. E.g. if I want to perform a sha256 hash on something 7 times, I can code it up this way:
<thing_i_want_to_hash> OP_SHA256 OP_SHA256 OP_SHA256 OP_SHA256 OP_SHA256 OP_SHA256 OP_SHA256
See how much less space that took up? My VM-based for loop has 3120 lines of code, each of which eats up space in the blockchain and therefore must be paid for; this alternative version has 8 lines of code. That's because instead of these steps:
  • bodge together a for loop
  • set an initial number 7
  • run a function that performs sha256 on the input and then decrements the initial number
  • loop back and repeat that function until the initial number is a 0
...I'm just, um, running the function I want 7 times. It's so much easier and more efficient (not to mention way, way cheaper in terms of mining fees).
I think a possible drawback of the "write it out 7 times" method is that if you want to lock up money in a way that someone can only redeem it by performing some set of steps, you have to know in advance exactly what steps they can take, or you must write out a defined number of very specific options for them and put them between "if" tags. ("If the redeemer chooses option 3, run sha256 7 times, then check if the value is the one I was looking for, and if so, let them take the money.")
By doing it my way, with the loops, you give the redeemer a lot more flexibility. The witness program doesn't define the program they want to run, it just gives them access to a number of script functions and a number of loops, and then they can do those operations in any order they want as long as it ends up giving me the result I want.
I think that potentially gives us way more flexibility in terms of giving someone options for redeeming some money via a script without knowing in advance exactly what their script will be. I would love it if this unlocked the potential for things like scripted sidechain pegouts (where you require anyone who wants to take your "peg in" money to supply an SPV proof of some state on the sidechain in order to peg your money out), but that's probably a bit far fetched. In reality I'm not sure this is useful; but it certainly seems cool to me, and it might prove useful with more research.
Cool, thanks for the response.
I must have like 1000s of messages backlog in Ruben's telegram groups, I'll go check the more recent ones then.
reply