8

I noticed in the bitcoin wiki script page (https://en.bitcoin.it/wiki/Script) that there were two opcodes named:

OP_TOALTSTACK
OP_FROMALTSTACK

It looks like there is another stack that can be used separately as a data store, simply pushing and popping data. I've never heard of this before, but it seems like a very useful feature.

Can anyone verify that this is what the alt stack is actually meant to be used for? If not for just pushing and popping data, what is it for? Do any specific use cases come to mind?

7

Here's where they're defined:

            case OP_TOALTSTACK:
            {
                if (stack.size() < 1)
                    return false;
                altstack.push_back(stacktop(-1));
                popstack(stack);
            }
            break;

            case OP_FROMALTSTACK:
            {
                if (altstack.size() < 1)
                    return false;
                stack.push_back(altstacktop(-1));
                popstack(altstack);
            }
            break;

Example:

Stack:
Alternate Stack:
Script: OP_1 OP_2 OP_TOALTSTACK

.

Stack: 01
Alternate Stack:
Script: OP_2 OP_TOALTSTACK

.

Stack: 01 02
Alternate Stack:
Script: OP_TOALTSTACK

.

Stack: 01
Alternate Stack: 02
Script: 

what is it for? Do any specific use cases come to mind?

It's... use-impaired. 99% of the time, you can avoid using OP_(TO|FROM)ALTSTACK by putting things onto the stack in a different order. There are 18 stack manipulation operators, but only one (OP_DUP) is used with any regularity. I'm of the opinion that Bitcoin scripting is overcomplicated for its intended use.

  • 4
    +1, but in stack-based languages, whether or not necessary, it is often convenient to have access to a second stack. For example, in Forth, it is a common idiom to (ab)use the return stack (>R, R>) for storing temporary data. See forth.com/starting-forth/sf5/sf5.html for an example. The designers may have had this in mind. Anyway, given the difficulty (chain fork) of adding additional features to the scripting language, one can understand that the designers had an incentive to overdesign. – Nate Eldredge Oct 26 '14 at 16:08
  • @Nick, I see where you're coming from when there are really only a few types of standard transactions, but some think the Bitcoin scripting language is too simple for its intended use. e.g. Ethereum. I think Satoshi found a good balance with the Bitcoin scripting language, making it flexible but also statically analyzable. – morsecoder Oct 27 '14 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.