12

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?

Michael Folkson
  • 15,313
  • 3
  • 17
  • 53
morsecoder
  • 14,168
  • 2
  • 42
  • 94

1 Answers1

9

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.

Nick ODell
  • 29,396
  • 11
  • 72
  • 130
  • 5
    +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 http://www.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